前言
在项目的开发过程中,或多或少都会涉及到文件的上传和下载,比如说(Excel、word)等等,这篇文章主要记录在SpringBoot项目中,如何实现单个文件的上传和下载,以及多文件的上传。
PS:本文中的前端展示界面使用thymeleaf模板。不会的可以参考右边的文章?SpringBoot整合Thymeleaf模板
Thymeleaf模板
<body>
<h3>单个文件上传</h3>
<form action="/file/upload" enctype="multipart/form-data" method="post">
文件选择:<input type="file" name="file">
<input type="submit" value="上传">
</form>
<h3>多个文件上传</h3>
<form action="/file/uploadAll" enctype="multipart/form-data" method="post">
文件选择1:<input type="file" name="fileName"><br>
文件选择2:<input type="file" name="fileName"><br>
文件选择3:<input type="file" name="fileName">
<input type="submit" value="上传">
</form>
<a href="/file/download">下载</a>
</body>
Controller
@Controller
@RequestMapping("/file/")
public class FileController {
/**
* 文件下载
*/
@RequestMapping("download")
public void download(HttpServletResponse response) {
//被下载的文件路径
String filePath = "D:/upload/";
//被下载的文件名
String fileName = "123.txt";
//文件对象
File file = new File(filePath+fileName);
//设置类型为强制下载
response.setContentType("application/force-download");
//设置下载后的文件名
response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
//设置编码格式
response.setCharacterEncoding("UTF-8");
//文件下载
try {
//缓冲区读取数据
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
//输出流
OutputStream os = response.getOutputStream();
//创建字节数组
byte[] buff = new byte[(int)file.length()];
//读取
int i = 0;
while((i=bis.read(buff)) > 0) {
os.write(buff);
}
os.close();
bis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 多个文件上传
* 1、使用@RequestParam("fileName")注解方式获取文件集合files
* public String uploadAll(@RequestParam("fileName") List<MultipartFile> files) {}
* 2、使用HttpServletRequest获取文件集合files
* public String uploadAll(HttpServletRequest request) {
* List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
*/
@RequestMapping("uploadAll")
@ResponseBody
public String uploadAll(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
//上传文件路径
String filePath = "D:/upload/";
MultipartFile file = null;
//上传成功个数
int num = 0;
for (int i = 0; i < files.size(); i++) {
//获取第i个文件
file = files.get(i);
//获取文件名
String fileName = file.getOriginalFilename();
//文件的绝对路径
fileName = filePath + new SimpleDateFormat("YYYYMMddHHmmss").format(new Date()) + fileName;
//获取当前文件对象
File dest = new File(fileName);
//判断父目录是否存在,不存在就创建
if(!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
num++;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "文件上传 - 共"+files.size()+"个文件,成功"+num+"个,失败"+(files.size()-num)+"个";
}
/**
* 单个文件上传
*/
@RequestMapping("upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
//获取文件名
String fileName = file.getOriginalFilename();
//上传的文件路径
String filePath = "D:/upload/";
//上传文件的绝对路径
fileName = filePath + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + fileName;
//获取文件对象
File dest = new File(fileName);
//判断父目录是否存在,不存在则创建
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdir();
}
//上传文件
try {
file.transferTo(dest);
return "文件上传成功!";
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "文件上传失败!";
}
}
Exception
上传时遇到报错org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException
原因:文件上传过大,SpringBoot的默认上传文件的大小是2m 如果你上传的文件超过了2m就会出现这样的错误。
解决方案:设置文件的上传大小。?
关于上传下载的一些配置
1、配置文件方式配置
spring:
servlet:
multipart:
enabled: true #是否支持多个文件上传(默认true)
max-file-size: 1MB #设置上传的单个文件的大小上限
max-request-size: 10MB #设置总上传的大小上限
2、自定义配置类
ps:自定义配置类已过时,建议使用配置文件方式进行配置。
/**
* 文件上传下载的自定义配置类
*/
@Configuration
public class MultipartFileProperties {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//设置单个文件大小
factory.setMaxFileSize("1024KB");
//设置总上传的大小
factory.setMaxRequestSize("1024KB");
return factory.createMultipartConfig();
}
}
本文为初学者学习记录,有什么讲的不对的地方欢迎指出。谢谢!