SpringMVC:文件上传下载如何实现?
一、文件下载
如果在响应时候没有设置响应头中的Content-Disposition属性,则会使用默认值inline,此时客户端访问静态资源的时候,能解析显示的就会解析显示,不能解析显示的就会进行下载。
为了实现下载功能,我们需要设置属性值为:attachement;filename=文件名。
例子:
1、页面。
<a href="download?fileName=ya.jpg">下载</a>
2、文件位置。
3、响应器。
@RequestMapping("download")
public void download(String fileName,HttpServletRequest request,HttpServletResponse response) throws IOException {
//设置响应头
response.setHeader("Content-Disposition", "attachement;filename="+fileName);
//获取响应流
ServletOutputStream os = response.getOutputStream();
//获取到文件的真实地址,在项目的files文件夹下
String path = request.getServletContext().getRealPath("files");
//创建文件对象
File file = new File(path,fileName);
//转为字节数组
byte[] bytes = FileUtils.readFileToByteArray(file);
//写入响应流中
os.write(bytes);
os.flush();
os.close();
}
二、文件上传
步骤:
1、表单的enctype属性设置为 multipart/form-data 表示上传的表单以二进制流的形式上传,method为post。
2、在springmvc配置文件中注册CommonsMultipartResolver文件解析器。
例子:
1、页面。
<form action="upload" enctype="multipart/form-data" method="post"> 姓名:<input name="name" type="text"/> 文件:<input name="file" type="file"/> <input type="submit" value="上传文件"> </form>
2、响应器。
@RequestMapping("upload")
public void upload(MultipartFile file,String name,HttpServletRequest request) throws IOException {
//获取文件名
String fileName = file.getOriginalFilename();
System.out.println("接收到"+name+"上传的文件:"+fileName);
//获取后缀
String suffix = fileName.substring(fileName.lastIndexOf("."));
//控制文件格式
if(suffix.equalsIgnoreCase(".jpg")){
//避免多次上传同名文件覆盖
String uuid = UUID.randomUUID().toString();
//存入
FileUtils.copyInputStreamToFile(file.getInputStream(),new File(
request.getServletContext().getRealPath("files")+"/"+uuid+suffix));
}
}

浙公网安备 33010602011771号