文件上传
第一步:导入spring boot依赖(如果使用thymeleaf模板就加下面相关的thymeleaf依赖及配置,如果使用jsp就不用加thymeleaf相关)
<!-- 文件上传 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
第二步:修改application.properties配置文件
# 禁用 thymeleaf 缓存
spring.thymeleaf.cache=false
# 是否支持批量上传 (默认值 true)
spring.servlet.multipart.enabled=true
# 上传文件的临时目录 (一般情况下不用特意修改)
spring.servlet.multipart.location=
# 上传文件最大为 1M (默认值 1M 根据自身业务自行控制即可)
spring.servlet.multipart.max-file-size=1048576
# 上传请求最大为 10M(默认值10M 根据自身业务自行控制即可)
spring.servlet.multipart.max-request-size=10485760
# 文件大小阈值,当大于这个阈值时将写入到磁盘,否则存在内存中,(默认值0 一般情况下不用特意修改)
spring.servlet.multipart.file-size-threshold=0
# 判断是否要延迟解析文件(相当于懒加载,一般情况下不用特意修改)
spring.servlet.multipart.resolve-lazily=false
如默认只允许1M以下的文件,当超出该范围则会抛出下述错误
org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (20738021) exceeds the configured maximum (10485760)
第三步:jsp或模板页面
<%@page isELIgnored="false" language="java" contentType="text/html; utf-8" pageEncoding="UTF-8" %>
<script src="/js/jquery-1.4.2.js"></script>
<script src="/js/jquery.form.js"></script>
<script>
$(function() {
$("#formLogin").bind("submit", function() {
$(this).ajaxSubmit({
//dataType: "json", //html(默认), xml, script, json...接受服务端返回的类型
//提交成功后的回调函数
success : function(data, status, xhr, $form) {
alert(data);
// $("#uploadimg").attr("src",data);
}
});
return false; //阻止表单默认提交
});
$("#manyfiles").bind("click",function () {
$("#filea").clone().appendTo("#formLogin");
});
});
</script>
<body>
<h2>单一文件上传示例</h2>
<div>
<form method="POST" enctype="multipart/form-data"
action="/upload1">
<p>
文件1:<input type="file" name="file" /> <input type="submit"
value="上传" />
</p>
</form>
</div>
<hr />
<h2>批量文件上传示例 <input type="button" value="增加" id="manyfiles"></h2>
<div>
<form method="POST" enctype="multipart/form-data"
action="/upload2" id="formLogin">
<p id="filea">
文件:<input type="file" name="file" />
</p>
<p>
文件:<input type="file" name="file" />
</p>
<p>
<input type="submit" value="上传" />
</p>
</form>
</div>
</body>
第四步:处理控制器
// 单个文件上传
@PostMapping("/upload1")
public Map<String, String> upload1(@RequestParam("file") MultipartFile file)
throws IOException {
// 将文件写入到指定目录(具体开发中有可能是将文件写入到云存储/或者指定目录通过 Nginx 进行 gzip
// 压缩和反向代理,此处只是为了演示故将地址写成本地电脑指定目录)
file.transferTo(new File("d:/" + file.getOriginalFilename()));
Map<String, String> result = new HashMap<>(16);
result.put("contentType", file.getContentType());
result.put("fileName", file.getOriginalFilename());
result.put("fileSize", file.getSize() + "");
return result;
}
// 多个文件上传
@PostMapping("/upload2")
public List<Map<String, String>> upload2(
@RequestParam("file") MultipartFile[] files) throws IOException {
if (files == null || files.length == 0) {
return null;
}
List<Map<String, String>> results = new ArrayList<>();
for (MultipartFile file : files) {
file.transferTo(new File("d:/" + file.getOriginalFilename()));
Map<String, String> map = new HashMap<>(16);
map.put("contentType", file.getContentType());
map.put("fileName", file.getOriginalFilename());
map.put("fileSize", file.getSize() + "");
results.add(map);
}
return results;
}
文件下载
@RestController
public class Hello2 {
// 文件下载
@RequestMapping("/downloadfile")
public byte[] downloadFile(HttpServletResponse response) throws IOException {
response.setContentType("application/x-tar;charset=utf-8");
response.setHeader("Content-disposition", "attachment;filename="
+ java.net.URLEncoder.encode("过滤器杠和杠星区别.doc", "UTF-8"));
final File tempFile = new File("d:/过滤器杠和杠星区别.doc");
return FileCopyUtils.copyToByteArray(tempFile);
}
//下载
@RequestMapping("/downloadfile")
public void hello(HttpServletResponse resp) throws IOException {
resp.setContentType("application/x-tar;charset=utf-8");
resp.setHeader("Content-disposition", "attachment;filename="
+ java.net.URLEncoder.encode("优化.png", "UTF-8"));
// org.springframework.core.io.Resource res = new ClassPathResource("C:\\Users\\Administrator\\Desktop\\工作簿1.xlsx");
// FileCopyUtils.copy(res.getInputStream(), resp.getOutputStream());
FileCopyUtils.copy(new FileInputStream("C:\\Users\\Administrator\\Desktop\\工作簿1.xlsx"), resp.getOutputStream());
}