springboot文件的上传与下载
1.springboot支持的文件上传
springboot提供的文件串串自动化配置类MultipartAutoConfiguration中,默认采用StandardServletMultipartResolver,上传文件可以做到零配置。
2.单多文件上传下载 html页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<p>单文件上传</p>
<form action="/uploadfile" method="POST" enctype="multipart/form-data">
文件:<input type="file" name="file"/>
<input type="submit"/>
</form>
<hr/>
<p>第一种多文件上传 ctrl选中多个文件</p>
<form action="/batchupload" method="post" enctype="multipart/form-data">
<input class="image" type="file" name="uploadFiles" value="请选择文件" multiple>
<input type="submit" value="上传">
</form>
<hr/>
<p>文件下载</p>
<a th:href="@{/download/qq1.jpg}">下载文件</a>
<hr/>
<p>第二种多文件下载,多个选择框</p>
<form method="POST" enctype="multipart/form-data" action="/batchupload2">
<p>文件1:<input type="file" name="file"/></p>
<p>文件2:<input type="file" name="file"/></p>
<p><input type="submit" value="上传"/></p>
</form>
</body>
</html>
3.controller 层
对于文件上传后保存的位置,我选择了保存此工程下的upload文件夹,可以参考getPath()方法。
从代码中可以看出对于上传文件,功能代码只需要 uploadFile.transferTo(folder); 这一句,可以看出springboot做了良好的配置,其他的都是设置路径,文件名之类的了。
对于多文件上传,提供了两种方式。
@RestController
public class UploadController {
SimpleDateFormat sdf = new SimpleDateFormat("\\yyyy\\MM\\dd\\");
@PostMapping(value = "/uploadfile")
public String upload(MultipartFile uploadFile) throws FileNotFoundException {
if (uploadFile.isEmpty()) {
return "文件为空";
}
File folder = new File(getPath(uploadFile));
if (!folder.getParentFile().exists()) {
folder.getParentFile().mkdirs();
}
try {
uploadFile.transferTo(folder);
return "success" + folder.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
return "上传失败";
}
}
@GetMapping("/download/{filename}")
public String downloadFile(HttpServletRequest request, HttpServletResponse response,@PathVariable("filename" ) String filename) {
String fileName = "yiyi.jpeg";// 文件名
if (fileName != null) {
//设置文件路径
File file = new File("F:\\"+filename);
//File file = new File(realPath , fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
return "下载成功";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return "下载失败";
}
@PostMapping(value = "/batchupload")
public String batchupload(MultipartFile[] uploadFiles,HttpServletRequest request) throws FileNotFoundException {
MultipartFile file = null;
for (int i = 0; i < uploadFiles.length; i++) {
file = uploadFiles[i];
File folder = new File(getPath(file));
if (!folder.getParentFile().exists()) {
folder.getParentFile().mkdirs();
}
try {
file.transferTo(folder);
System.out.println("第"+i+"个文件串串成功");
} catch (IOException e) {
e.printStackTrace();
return "第"+i+"上传失败";
}
}
return "success";
}
@PostMapping(value = "/batchupload2")
public String handleFileUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i = 0; i < files.size(); ++i) {
file = files.get(i);
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(new FileOutputStream(
new File(getPath(file))));//设置文件路径及名字
stream.write(bytes);// 写入
stream.close();
} catch (Exception e) {
stream = null;
return "第 " + i + " 个文件上传失败 ==> "
+ e.getMessage();
}
} else {
return "第 " + i
+ " 个文件上传失败因为文件为空";
}
}
return "上传成功";
}
/**
* @Description: 封装文件路径组成
* @author: zfc
* @date: 2019/7/20 19:54
* @param:
*/
protected String getPath(MultipartFile uploadFile) throws FileNotFoundException {
// 获取文件名
String fileName = uploadFile.getOriginalFilename();
// 获取文件后缀
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 路径夹
String filepath = getJarRootPath() + "\\upload";
// 时间
String format = sdf.format(new Date());
// 文件路径
String path = filepath + format + fileName;
return path;
}
/**
* @Description: 获取项目路径
* @author: zfc
* @date: 2019/7/20 19:50
* @param:
* @return:
*/
protected String getJarRootPath() throws FileNotFoundException {
String path = ResourceUtils.getURL("classpath:").getPath();
File rootFile = new File(path);
if (!rootFile.exists()) {
rootFile = new File("");
}
return rootFile.getAbsolutePath();
}
}
4.对上传文件的细节配置
在application.properties 配置即可
#开启文件上传
spring.servlet.multipart.enabled=true
#单个文件最大1MB
spring.servlet.multipart.max-file-size=1MB
#多文件上传的总大小10MB
spring.servlet.multipart.max-request-size=10MB
#文件是否延迟解析
spring.servlet.multipart.resolve-lazily=false