目录
1.在配置文件中写好物理路径和访问路径
(自定义)file:
uploadPath: D:/upload/img/ 物理路径
path: /file/** 访问路径
2.写配置文件
package com.example.uploaddemo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Value("${file.uploadPath}")
String filelocation;
@Value("${file.path}")
String filepath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//匹配到resourceHandler,将URL映射至location,也就是本地文件夹
registry.addResourceHandler(filepath).addResourceLocations("file:" + filelocation);
//这里最后一个file:不能不写
}
}
控制层取到和配置文件中的物理路径和访问路径,并且写在方法中。
3.页面上传
在页面写好上传和保存,上传到对应的路径,对应好上传的数组名
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>上传图片</title>
</head>
<body>
<form th:action="@{/goUploadImg}" method="post" enctype="multipart/form-data">
<input type="file" value="上传" name="fileUpload">
//将页面图片路径和前端存的路径绑定
<img th:src="@{/file/{header}(header=${filename})}" height="200px" width="200px">
<input type="submit" value="保存">
</form>
</body>
</html>
4.控制层
// 上传头像
@RequestMapping("/goUploadImg")
public String goUploadImg(MultipartFile[] fileUpload, Model model) {
String allFile = "";
//上传多个文件时,遍历存入
for (MultipartFile file : fileUpload) {
String filename = file.getOriginalFilename();
String newFileName = "22610302150754.jpg";
String uploadDir = "D:/upload/img/";//存入地址
File fileDir = new File(uploadDir);
if (!fileDir.exists()) //首先检查上传的文件夹是否存在
fileDir.mkdirs(); //不存在就直接创建
try {
//上传指定的新的文件名的文件到指定的文件夹下
allFile += filename + ",";
file.transferTo(new File(uploadDir + newFileName));
//路径存到前端页面上
model.addAttribute("filename", newFileName);
model.addAttribute("uploadStatus", allFile + "文件上传成功");
} catch (IOException e) {
model.addAttribute("uploadStatus", allFile + "文件上传失败");
e.printStackTrace();
}
}
return "uploadImg";
}
@RequestMapping("/img")
public String goimg(){
return "uploadImg";
}
}
上传name和方法中数组名字相同
5.效果