SpringMVC的文件上传和下载案例
上传步骤
1. 引入依赖 commons-fileupload
2. 编写上传页面
3. 表单 method="post" enctype="multipart/form-data" input type='file'
4. 编写controller时考虑文件重名问题,以及文件在服务器的绝对路径
5. 编写文件上传的解析器 id必须为multipartResolver
6. 测试
下载步骤
1. 编写页面
2. 设置响应对象的编码
3. 测试
controller
package com.codegzy.controller;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.UUID;
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest request){
String originalFilename = file.getOriginalFilename();
//获取目录在服务器的绝对路径
String realPath = request.getRealPath("/upload");
//防止文件重名覆盖问题
String extension = FilenameUtils.getExtension(originalFilename);
String newfilename = UUID.randomUUID().toString().replace("-","") + "." + extension;
//将不同天上传的文件分开
LocalDate now = LocalDate.now();
File dirdate = new File(realPath, now.toString());
if (!dirdate.exists()){
dirdate.mkdirs();
}
try {
file.transferTo(new File(dirdate,newfilename));
} catch (IOException e) {
e.printStackTrace();
}
return "index";
}
@RequestMapping("/download")
public void download(String openStyle,String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
openStyle = openStyle == null ? "inline" : "attachment";
String realPath = request.getSession().getServletContext().getRealPath("/download");
//输入流读取文件
FileInputStream inputStream = new FileInputStream(new File(realPath, filename));
//设置相应
response.setContentType("text/plain;charset=UTF-8");
//设置下载格式 attachment 附件 inline 在线
//对文件进行编码防止中文文件名乱码问题
response.setHeader("content-disposition",openStyle + ";filename=" + URLEncoder.encode(filename,"UTF-8"));
//获取输出流
ServletOutputStream outputStream = response.getOutputStream();
//利用工具类
IOUtils.copy(inputStream,outputStream);
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
//传统下载的方法
// int len = 0;
// byte[] bytes = new byte[1024];
// while (true){
// len = inputStream.read(bytes);
// if (len == -1) {
// break;
// }
// outputStream.write(bytes,0,len);
// }
// inputStream.close();
// outputStream.close();
}
@RequestMapping("/newfile")
public String newfile(){
throw new RuntimeException("出错了");
}
}
springmvc.xml
<!-- 文件上传解析器-->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<!-- 限制文件上传最大为20M,超过20M报错-->
<property name="maxUploadSize" value="20971520"/>
</bean>
页面
<body>
<h2>文件上传</h2>
<form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传文件">
</form>
</body>
<body>
<h2>文件下载</h2>
abc.txt<a href="${pageContext.request.contextPath}/file/download?filename=abc.txt">在线打开</a> <a href="${pageContext.request.contextPath}/file/download?filename=abc.txt&openStyle=a">附件下载</a>
自我接收.txt<a href="${pageContext.request.contextPath}/file/download?filename=自我接收.txt">在线打开</a> <a href="${pageContext.request.contextPath}/file/download?filename=自我接收.txt&openStyle=a">附件下载</a>
</body>