SpringMvc文件的上传和下载
前言
文件的上传和下载在项目开发中十分的常见,今天我们一起来看一下SpringMvc是如何实现文件的上传和下载的
提示:本文仅提供部分核心代码
一、前提准备
引入文件上传和下载所需要的依赖,编写配置文件。
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version> </dependency>
<dependency>
在SpringMvc配置文件中添加
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--默认编码-->
<property name="defaultEncoding" value="utf-8"></property>
<!--最大上传数据大小-->
<property name="maxUploadSize" value="1024000000"></property>
</bean>
二、文件上传
1.页面
<body>
<form method="post" action="/upload.do" enctype="multipart/form-data">
请选择文件:
<input type="file" name="multipartFile">
<input type="submit" value="上传">
</form>
</body>
注:此时form表单的请求方式应为post,并且要指定属性enctype="multipart/form-data"属性
2.处理器
代码如下(示例):
package com.offcn.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
@RestController
@SessionAttributes(names = "user")
public class MyTestController {
@RequestMapping("/upload")
public String upLoad(MultipartFile multipartFile, HttpServletResponse response){
//创建一个文件夹用来保存上传的文件
String path = "F:\\1012";
//判断文件夹是否存在,若不存在就先创建
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
//获取文件名字
String realFileName = multipartFile.getOriginalFilename();
//要上传指定目录的文件,注意这里没有考虑加上UUID等...
File realFile = new File(file,realFileName);
try {
multipartFile.transferTo(realFile);
return "success";
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
}
}
下载
@RequestMapping("/downLoadFile")
public ResponseEntity<byte[]> downLoadFile(String fileName) throws Exception {
//目标文件夹
String downloadDir = "F:\\1012";
//目标文件
File downLoadFile = new File(downloadDir, fileName);
//编码转换
fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
//设置响应头
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(downLoadFile), headers, HttpStatus.OK);
}