spring boot实现文件上传下载
spring boot 引入”约定大于配置“的概念,实现自动配置,节约了开发人员的开发成本,并且凭借其微服务架构的方式和较少的配置,一出来就占据大片开发人员的芳心。大部分的配置从开发人员可见变成了相对透明了,要想进一步熟悉还需要关注源码。
1.文件上传(前端页面):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/testUpload" method="POST" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" />
</form>
<a href="/testDownload">下载</a>
</body>
</html>
表单提交加上enctype="multipart/form-data"很重要,文件以二进制流的形式传输。
2.文件上传(后端java代码)支持多文件
Way1.使用MultipartHttpServletRequest来处理上传请求,然后将接收到的文件以流的形式写入到服务器文件中:
@RequestMapping(value="/testUpload",method=RequestMethod.POST)
public void testUploadFile(HttpServletRequest req,MultipartHttpServletRequest multiReq) throws IOException{
FileOutputStream fos=new FileOutputStream(new File("F://test//src//file//upload.jpg"));
FileInputStream fs=(FileInputStream) multiReq.getFile("file").getInputStream();
byte[] buffer=new byte[1024];
int len=0;
while((len=fs.read(buffer))!=-1){
fos.write(buffer, 0, len);
}
fos.close();
fs.close();
}
Way2.也可以这样来取得上传的file流:
// 文件上传
@RequestMapping("/fileUpload")
public Map fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
Map result = new HashMap();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式
String dateDir = df.format(new Date());// new Date()为获取当前系统时间
String serviceName = UuidUtil.get32UUID()
+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
File tempFile = new File(fileDir + dateDir + File.separator + serviceName);
if (!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdirs();
}
if (!file.isEmpty()) {
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
// "d:/"+file.getOriginalFilename() 指定目录
out.write(file.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
result.put("msg", "上传失败," + e.getMessage());
result.put("state", false);
return result;
} catch (IOException e) {
e.printStackTrace();
result.put("msg", "上传失败," + e.getMessage());
result.put("state", false);
return result;
}
result.put("msg", "上传成功");
String fileId = Get8uuid.generateShortUuid();
String fileName = file.getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
String fileUrl = webDir + dateDir + '/' + serviceName;
uploadMapper.saveFileInfo(fileId, serviceName, fileType, fileUrl);
result.put("state", true);
return result;
} else {
result.put("msg", "上传失败,因为文件是空的");
result.put("state", false);
return result;
}
3.application.properties配置文件
#上传文件大小设置
multipart.maxFileSize=500Mb
multipart.maxRequestSize=500Mb
4.文件下载将文件写到输出流里:
@RequestMapping(value="/testDownload",method=RequestMethod.GET)
public void testDownload(HttpServletResponse res) throws IOException{
File file = new File("C:/test.txt");
resp.setHeader("content-type", "application/octet-stream");
resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = resp.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5.获取文件大小
// 文件大小转换
DecimalFormat df1 = new DecimalFormat("0.00");
String fileSizeString = "";
long fileSize = file.getSize();
if (fileSize < 1024) {
fileSizeString = df1.format((double) fileSize) + "B";
} else if (fileSize < 1048576) {
fileSizeString = df1.format((double) fileSize / 1024) + "K";
} else if (fileSize < 1073741824) {
fileSizeString = df1.format((double) fileSize / 1048576) + "M";
} else {
fileSizeString = df1.format((double) fileSize / 1073741824) + "G";
}
如果是File类则fileSize=file.length()。
spring boot实现文件上传下载的更多相关文章
- Spring Boot 教程 - 文件上传下载
在日常的开发工作中,基本上每个项目都会有各种文件的上传和下载,大多数文件都是excel文件,操作excel的JavaAPI我用的是apache的POI进行操作的,POI我之后会专门讲到.此次我们不讲如 ...
- Spring Boot入门——文件上传与下载
1.在pom.xml文件中添加依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...
- spring boot:单文件上传/多文件上传/表单中多个文件域上传(spring boot 2.3.2)
一,表单中有多个文件域时如何实现说明和文件的对应? 1,说明和文件对应 文件上传页面中,如果有多个文件域又有多个相对应的文件说明时, 文件和说明如何对应? 我们在表单中给对应的file变量和text变 ...
- spring mvc注解文件上传下载
需要两个包: 包如何导入就不介绍了,前端代码如下(一定要加enctype="multipart/form-data"让服务器知道是文件上传): <form action=&q ...
- Spring Boot—04文件上传
package com.smartmap.sample.ch1.controller.view; import java.io.File; import java.io.IOException; im ...
- spring mvc 实现文件上传下载
/** * 文件上传 * @param pictureFile */ @RequestMapping("/reportupload") public ResponseInfo up ...
- spring boot Tomcat文件上传找不到零时文件夹
springboot项目上传文件是找不到零时文件夹 1.本身启动jar包时内置Tomcat没有创建零时文件夹 2.在zuul网关级别没有创建零时文件夹 处理方案: -Djava.io.tmpdir=/ ...
- Spring Boot RestTemplate文件上传
@ResponseBody @RequestMapping(value = "/upload.do", method = RequestMethod.POST) public St ...
- Spring boot设置文件上传大小限制
原文:https://blog.csdn.net/lizhangyong1989/article/details/78586421 Spring boot1.0版本的application.prope ...
随机推荐
- 【06】sass编译工具(弃)
[06]编译工具(弃) SASS转译工具 除了使用sass命令来转译SASS文件之外,还可以借助第三方工具完成,目前世面上较为流行的转译工具主要有: Compass.app Scout Codekit ...
- Fidder详解-抓取HTTPS清求(Web/App)抓包分析(靠谱篇)
为什么要学Fidder抓包? 学习接口,必须要学http协议,不要求您对协议的掌握有多深.只是希望你能够了解什么是协议.协议的报文.状态码等等!本文通过抓包工具Fidder带你进入接口的大门.我们通过 ...
- 大数据学习——linux常用命令(三)
三 文件操作 1创建文件 touch somefile.txt 创建一个空文件somefile.txt > 重定向操作符 echo "woshiwoa"> some.t ...
- 【转载】CentOS6.5升级手动安装GCC4.8.2
一.简易安装 操作环境 CentOS6.5 64bit,原版本4.4.7,不能支持C++11的特性~,希望升级到4.8.2 不能通过yum的方法升级,需要自己手动下载安装包并编译 1.1 获取安装包并 ...
- POJ-1861,Network,最小生成树水题,,注意题面输出有问题,不必理会~~
Network Time Limit: 1000MS Memory Limit: 30000K Special Judge http://poj.org/problem?id=1 ...
- bzoj 2721[Violet 5]樱花 数论
[Violet 5]樱花 Time Limit: 5 Sec Memory Limit: 128 MBSubmit: 671 Solved: 395[Submit][Status][Discuss ...
- SpringBoot配置Bean的两种方式--注解以及配置文件
一.注解方式 编写实体类: package com.example.bean; import org.springframework.boot.context.properties.Configura ...
- CodeForces - 320B Ping-Pong (Easy Version)
题目最开始 完全不懂 配合案例也看不懂-_- 总之就是用传递性 问能否从a区间到b区间 dfs(x,y) 走遍与第x区间所有的 联通区间 最后检验 第y区是否被访问过 是一道搜索好题 搜索还需加强 # ...
- MySQL介绍及安装&MySQL软件基本管理
mysql介绍 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下公司.MySQL 最流行的关系型数据库管理系统,在 WEB 应用方面MySQL是最好 ...
- mysql查所有列名
查询该视图 information_schema.columns 该有的都有 desc information_schema.columns; select * from information_ ...