文件上传下载1、上传2、下载
1、上传
Spring MVC为文件上传提供了直接的支持,这种支持是用即插即用的MultipartResolver实现的。Spring MVC使用Apache Commons FileUpload技术实现了一个MultipartResolver实现类:CommonsMultipartResolver。因此,SpringMVC的文件上传还需要依赖Apache Commons FileUpload的组件。
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
配置文件
<!--200*1024*1024即200M resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="209715200" />
<property name="defaultEncoding" value="UTF-8" />
<property name="resolveLazily" value="true" />
</bean>
方法
public void upload(MultipartFile file){
if(!file.isEmpty()){
//设置存储文件的地址
String path = request.getSession().getServletContext().getRealPath("/upload/");
File filePath = new File(path);
if (!filePath.exists()){
filePath.mkdirs();
}
//设置上传后的文件的名称
String fileName = new Date().getTime()+file.getOriginalFilename();
//上传
file.transferTo(new File(path+fileName));
}
}
2、下载
@RequestMapping("download")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
//设置存储文件的地址
String path = request.getSession().getServletContext().getRealPath("/upload/1524152408378IntelliJ IDEA2017.3激活.pdf");
File file=new File(path);
HttpHeaders headers = new HttpHeaders();
String fileName=new String("1524152408378IntelliJ IDEA2017.3激活.pdf".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
通用 java 下载
@RequestMapping("download")
public void download(HttpServletRequest request) throws IOException {
String path = request.getSession().getServletContext().getRealPath("/upload/1524152408378IntelliJ IDEA2017.3激活.pdf");
String fileName=new String("1524152408378IntelliJ IDEA2017.3激活.pdf".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(path));
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}