ssm下的文件上传和下载
1. 文件上传
1.1 文件上传需要的依赖
文件上传需要使用到 commons-fileupload
和 commons-io
两个 jar
包。
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
1.2 在项目中配置存放上传文件的文件夹
# config.properties
# 配置文件
file.save.dir=E:\\upload
注:在properties文件中设置配置参数之后,在spring-mvc.xml的配置文件中加载,就可以直接使用注解注入到参数。
<!--设置配置文件,能够使用@Value("${ }")进行注入String值-->
<context:property-placeholder location="classpath:config.properties" />
1.3 spring-mvc.xml中添加的配置
spring ioc的set注入:
<!--需要注意:这里的id值只能为multipartResolver,修改就要报错,因为spring内部只会去调用这个id-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<!--内存中可用大小:3 * 1024 * 1024 = 3145728 = 3M-->
<property name="maxInMemorySize" value="3145728" />
<!--设置临时存储目录,当上传文件大小超过内存中可使用大小时将产生临时文件-->
<property name="uploadTempDir" value="/upload"/>
<!--50 * 1024 * 1024 = 52428800 = 50M -->
<!--最大上传大小-->
<property name="maxUploadSize" value="52428800" />
<!--单个文件大小-->
<property name="maxUploadSizePerFile" value="5242880" />
</bean>
1.4 编写控制器方法
@RestController
@RequestMapping("/file")
public class FileController {
@Value("${file.save.dir}")
private String saveDir; //配置文件中注入值
/**
* 文件上传
* @param file
* @return
* @throws IOException
*/
@PostMapping("/upload")
public String uploadFile(@RequestPart(name = "file") MultipartFile file) throws IOException {
File dir = new File(saveDir);
if(!dir.exists())
dir.mkdirs(); //确保父级文件夹存在
file.transferTo(new File(dir, file.getOriginalFilename()));
return "success";
}
}
1.5 简单的前端页面
index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="添加">
</form>
</body>
</html>
2. 文件下载
控制器方法:
@RestController
@RequestMapping("/file")
public class FileController {
@GetMapping("download/{fileName:.+}")
public ResponseEntity<byte[]> downloadFile(@PathVariable("fileName") String fileName,@RequestHeader("User-Agent") String userAgent) throws IOException {
File downloadFile = new File(saveDir, fileName);
byte[] data = FileUtils.readFileToByteArray(downloadFile);
//解决ie下载时文件名乱码的问题
userAgent = userAgent.toUpperCase();
//判断是否是ie浏览器
if (userAgent.contains("MSIE") || userAgent.contains("TRIDENT") || userAgent.contains("EDGE")) {
//IE下载文件名乱码可以直接通过URL编码解决
fileName = URLEncoder.encode(fileName, "UTF-8"); //StandardCharsets.UTF_8.name();
}else{
//其他浏览器需要使用转码进行解决
fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
headers.add("Content-Disposition", "attachment; filename=" + fileName);
return new ResponseEntity<>(data, headers, HttpStatus.OK);
}
}
下一章更新ssm框架下如何导入Excel表信息及下载信息生成Excel表