这篇文章是介绍使用SpringMVC实现文件的上传与下载,核心代码如下:
1、文件上传
环境搭建:
<!--文件上传jar包-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
web.xml配置文件代码:
<!-- 配置文件上传的视图解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
JSP页面代码:
<%@ page contentType="text/html; UTF-8" isELIgnored="false" pageEncoding="UTF-8" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload/u.do" method="post" enctype="multipart/form-data">
<input type="file" name="upload" />
<input type="submit" value="上传" />
</form>
</body>
</html>
Controller代码:
@Controller
@RequestMapping("/upload")
public class UploadController {
@RequestMapping("/u") //接受上传的文件
public String upload(MultipartFile upload, HttpSession session) throws Exception{
//根据相对路径获取绝对路径
String realPath = session.getServletContext().getRealPath("/upload");
//创建和上传文件 同名的文件, 此时的文件是为空的
//获取上传文件的名字
File file = new File(realPath + "/" + upload.getOriginalFilename());
//将上传的文件转入为空的文件中
upload.transferTo(file);
return "uploadOk";
}
}
注意事项:
1、创建的目标文件夹不能为空
2、SpringMVC默认是对于文件上传的大小没有限制可以通过属性进行设置
<property name="maxUploadSize" value="上传文件的文件大小"></property>
2、文件下载
@Controller
@RequestMapping("/download")
public class DownController {
@RequestMapping("/d")
public ResponseEntity<byte[]> download(String fileName, HttpSession session) throws Exception{
ServletContext servletContext = session.getServletContext();
//通过相对路径获取绝对路径
String realPath = servletContext.getRealPath("/upload");
//file没有则创建 有则代表此文件
File file = new File(realPath + "/" + fileName);
//把文件转化为字节数组
byte[] bytes = FileUtils.readFileToByteArray(file);
//设置下载时的请求头
HttpHeaders httpHeaders = new HttpHeaders();
//解决下载时中文乱码问题 //下载是的编码
String downname = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
//下载文件之后的打开方式 以附件的形式打开
httpHeaders.setContentDispositionFormData("attachmen",downname);
//设置下的方式 //采用二进制流的方式进行配置
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//告知SpringMVC框架状态已经准备好
return new ResponseEntity<byte[]>(bytes,httpHeaders, HttpStatus.CREATED);
}
}
访问方式:
http://localhost:8989/${pageContext.request.contextPath}/download/d.do?fileName=文件名