SpringMVC中文件的上传下载
文件下载
1.将控制器方法返回值设置为ResponseEntity
2.在控制器方法内部获取到文件的真实路径并且使用IO流读取文件到字节数组
3.创建HttpHeads对象添加请求头属性
属性为:Content-Disposition 值为attachment;filename=1.jpg //attachment是用附件的方式进行下载 filename是下载使用的文件名
4.使用文件字节数组,HttpHeads和HttpStatus枚举来创建ResponseEntity来返回
代码如下:
@Controller
public class FileController {
@RequestMapping("/filedownload")
public ResponseEntity downloadImg(HttpSession session) throws IOException {
//获取上下文
ServletContext servletContext = session.getServletContext();
//将工程中的文件路径转换为真实路径给IO流api使用
String realPath = servletContext.getRealPath("/static/img/1.jpg");
FileInputStream fileInputStream = new FileInputStream(realPath);
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
//创建响应头
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Disposition","attachment;filename=1.jpg");
HttpStatus ok = HttpStatus.OK;
//使用图片字节数组 请求头和状态码创建响应报文对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, ok);
return responseEntity;
}
}
文件上传
前端上传要求
必须使用post方式来提交数据 //get方式是将请求体参数拼接在地址栏,很明显文件上传无法做到
必须使用enctype来指定请求体数据格式且格式必须为multipart/form-data//enctype默认application/x-www-form-urlencoded,默认值的作用是将以字符串的形式来发送数据,而multipart/form-data图片非文本文件可以以二进制的数据发送到服务端
1.导入文件上传依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.配置上传文件解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
3.在控制器的方法中写入MultipartFile形参,这样文件上传解析器就可以将上传的文件封装成对象给我们使用
@RequestMapping("/upload")
@ResponseBody
public String uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
//获取文件名
String originalFilename = file.getOriginalFilename();//获取文件名
String realPath = request.getServletContext().getRealPath("/static/img");
file.transferTo(new File(realPath+File.separator+originalFilename));
return "success";
}