添加依赖
<!-- 文件上传所依赖的jar包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
在yml文件中进行配置
#fileupload的最大上传大小
spring:
servlet:
multipart:
max-file-size: 10485760
max-request-size: 10485760
文件上传的前台页面,form表单的enctype属性必须设置成multipart/form-data,前台使用了thymeleaf。
<form th:action="@{/saveFile}" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>图片:</td>
<td><input type="file" name="myfile"></td>
</tr>
<tr>
<td>发表用户头像:</td>
<td><input type="file" name="myfile"></td>
</tr>
<tr>
<td><input type="submit" value="提交"></td>
</tr>
</table>
</form>
上传图片的封装的方法
/**
* 上传多张图片
* @param file
* @param list
* @return
*/
private List<String> saveFile(MultipartFile file, List<String> list) throws IOException {
if (!file.isEmpty()) {
/*
项目服务器地址路径
*/
File pfile = new ClassPathResource("/static/img/").getFile();
//保存图片的路径
//获取原始图片的拓展名
String name = file.getOriginalFilename();
assert name != null;
// 截取文件后缀名
String originalFilename = name.substring(name.lastIndexOf("."));
//创建新的文件名字
String newFileName = UUID.randomUUID().toString().replace("-","") + originalFilename;
// 将文件名保存到数组中
list.add(newFileName);
//判断上传文件的保存目录是否存在
if (!pfile.exists() && !pfile.isDirectory()) {
System.out.println(pfile + "目录不存在,需要创建");
//创建目录
pfile.mkdir();
}
//创建文件
File targetFile = new File(pfile, newFileName);
//把本地文件上传到封装上传文件位置的全路径
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
调用图片上传方法并将图片名保存在数据库中
@PostMapping(value = "/saveFile")
public void insertArticle(@RequestParam("myfile") MultipartFile[] files,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;chartSet=UTF-8");
// 解决中文乱码问题
response.setCharacterEncoding("UTF-8");
List<String> list = new ArrayList<>();
if (files != null && files.length > 0) {
System.out.println("文件长度:"+files.length);
for (MultipartFile file : files) {
// 保存文件
saveFile(file, list);
}
}
}
图片的下载前台
<a th:href="@{/downLoad/p1.jpg}">下载文件</a>
后台
@GetMapping("downLoad/{filename}")
public void downLoad(@PathVariable("filename") String file,
HttpServletResponse response,
HttpServletRequest request) throws IOException {
// 获取文件服务器真实路径的字节流
InputStream inputStream = new ClassPathResource("/static/img/"+file).getInputStream();
//为了提高效率,使用字节缓冲流
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
//设置response响应头
String mimeType = request.getServletContext().getMimeType(file);
String userAgent = request.getHeader("User-Agent");
String fileName="";
// 解决浏览器下载中文乱码问题
if (userAgent.contains("MSIE") || userAgent.contains("Trident")||userAgent.contains("Edge")){
fileName= URLEncoder.encode(fileName, StandardCharsets.UTF_8);
}else {
fileName= new String(file.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
response.setHeader("content-type",mimeType);
// 下载文件能正常显示中文
response.setHeader("Content-Disposition","attachment;filename="+fileName);
//获取输出流
BufferedOutputStream outputStream =new BufferedOutputStream(response.getOutputStream());
// 将输入流写入到输出流中
IOUtils.copy(bufferedInputStream,outputStream);
// 关闭流
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}