环境配置
1、pom.xml中添加依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
2、配置xml配置文件
<!-- mvc文件管理器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置默认编码格式-->
<property name="defaultEncoding" value="UTF-8"/>
<!-- 设置最大文件上传大小-->
<property name="maxUploadSize" value="31457280"/>
<!-- 每次向内存写入大小-->
<property name="maxInMemorySize" value="40960"/>
</bean>
文件上传
//通过封装好的工具类MultipartFile实现文件上传
public void upload(MultipartFile filename) {
//获取文件名称
String name = filename.getOriginalFilename();
//获取随机名称作为存储名称,在服务器不需要查看,为了避免名称重复覆盖问题。
String uuid = UUID.randomUUID().toString();
try {
//保存文件到服务器磁盘
filename.transferTo(Path.of("服务器路径"+uuid));
} catch (IOException e) {
e.printStackTrace();
}
}
文件下载
public void downLoad(HttpServletResponse response){
String path = "服务器文件路径";
String name = "从数据库获取文件名";
//设置数据类型为二进制
response.setContentType("application/octet-stream");
//避免乱码,将名称转换为UTF-8
try {
name = new String(name.getBytes(StandardCharsets.UTF_8),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//避免浏览器直接打开文件,将其类型设置为附件形式,文件名为+name
response.addHeader("Content-Disposition","attachement;filename="+name);
//创建输出流
OutputStream out = null;
try {
//获取响应输出流
out = response.getOutputStream();
//将文件以二进制的形式写入流
out.write(FileUtils.readFileToByteArray(new File(path)));
//关闭流
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}