文件上传
- 引入依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
- form表单
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"> <br>
<input type="submit" value="上传">
</form>
- 后台代码
@ResponseBody
@RequestMapping("upload")
public String upload(MultipartFile file, HttpSession session){
//1. 获得 upload的路径
String realPath = session.getServletContext().getRealPath("/upload/img");
//2. 判断文件夹是否存在
File file1 = new File(realPath);
if(!file1.exists()){
file1.mkdirs();
}
//3.获取文件真实名字
String originalFilename = file.getOriginalFilename();
//4. 为了防止同一个文件多次上传发生覆盖 拼接时间戳
String name = new Date().getTime()+"_"+originalFilename;
//5.文件上传
try {
file.transferTo(new File(realPath,name));
} catch (IOException e) {
e.printStackTrace();
}
return "上传成功";
}
- 上传细节
-
默认上传单个文件大小: 1MB
-
默认批量上传文件大小为: 10MB
-
配置上传文件的大小(可选 KB MB GB TB)
-
配置上传文件大小
-
spring:
servlet:
multipart:
max-file-size: 10MB #单个文件大小 默认1MB
max-request-size: 90MB #同时上传多个文件大小 默认10MB
文件下载
- 后台实现
@RequestMapping("download")
public void download(String filename, HttpSession session, HttpServletResponse response) throws Exception {
//获得文件存放的路径
String realPath = session.getServletContext().getRealPath("/upload/file");
//创建文件夹
File file = new File(realPath, filename);
//设置响应类型及编码格式
String extension = FilenameUtils.getExtension(filename);
String mimeType = session.getServletContext().getMimeType("." + extension);
response.setContentType(mimeType+";charset=UTF-8");
//指定下载方式
response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(filename,"UTF-8"));
//下载
ServletOutputStream outputStream = response.getOutputStream();
FileUtils.copyFile(file, outputStream);
outputStream.close();
}