在我们实际工作中,web项目经常会用到文件的上传与下载,下面就是SpringMVC对文件上传下载的具体实现:
文件上传
1. 导入需要的jar包 或者配置Maven依赖
// Pom 文件依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2. spring ioc 配置需要的bean以及参数(上传解析器)
<!-- 定义文件上传解析器 此bean id必须为multipartResolver -->
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<beans:property name="defaultEncoding" value="UTF-8"/>
<!-- 设定文件上传的最大值为500000byte -->
<beans:property name="maxUploadSize" value="500000"/>
<!-- 设定文件上传时写入内存的最大值,如果小于这个参数不会生成临时文件,默认为10240 -->
<beans:property name="maxInMemorySize" value="1024"/>
</beans:bean>
3.编写上传用的jsp页面
必须为POST提交, enctype 必须为 multipart/form-data
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" contentType="text/html;charset=UTF-8"%>
<%@ page session="false" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/upload" method="post" enctype="multipart/form-data">
文件上传: <input type="file" name= "myfile">
<input type="submit" value="上传" name="sub">
</form>
</body>
</html>
4.编写文件上传控制器
@RequestMapping("/upload")
public String uplaod(MultipartFile myfile){
//获取文件名
String fileName = myfile.getOriginalFilename();
if(!myfile.isEmpty()){
try {
myfile.transferTo(new File("E://upload/", fileName));
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return "success";
}
这里需要注意的:控制器的方法参数名,必须与页面表单input的name属性相对应,如果对应不上 就会报错。
文件下载
在实际做项目中,下载文件基本都是通过查询数据库获得文件的所在路径或者二进制流,这里我们省略,直接从文件夹里找个文件
(一)使用Servlet Api实现文件下载:
1.获取文件路径
2.创建文件流对象(输入流对象) 读取文件信息到流对象中
3.创建输出流对象 将文件流信息写入到客户端
@RequestMapping("download")
public void download(HttpServletRequest req,HttpServletResponse resp) throws Exception{
//获取id
String id = req.getParameter("id");
System.out.println(id);
//获取文件
String filepath = "E://upload/jym.sql";
File file = new File(filepath);
String fileName = file.getName();
resp.setContentType("application/octet-stream");
resp.addHeader("Content-Disposition", "attachment; filename="+fileName);
//获取输入流
InputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while((len=in.read(b))!=-1){
out.write(b, 0, b.length);
}
out.flush();
out.close();
in.close();
}
web应用程序下载文件设置:
文件类型设置:通用类型 application/octet-stream
响应头信息的设置:Content-Disposition
下载文件名的设置:Content-Disposition:attachment;filename=xxxx.txt
(二)使用SpringMVC提供的Api实现文件下载(ResponseEntity类):
@RequestMapping("download2")
public ResponseEntity<byte[]> download2() throws IOException{
//根据id 获取文件对象
File file = new File("E://upload/jym.sql");
//获取文件名
String fileName = file.getName();
//创建HttpHeaders对象
HttpHeaders header = new HttpHeaders();
//设置响应头信息
header.setContentDispositionFormData("attachment", fileName);
//设置文件类型
header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//把文件对象转换成二进制数组
byte[] data= FileUtils.readFileToByteArray(file);
//把data字节数组通过构造器设置到entity对象中
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(data, header, HttpStatus.CREATED);
return entity;
}