实现文件上传主要依赖Spring的MultipartFile类,MultipartFile是SpringMVC提供简化上传操作的工具类。
在不使用框架之前,都是使用原生的HttpServletRequest来接收上传的数据,文件是以二进制流传递到后端的,然后需要我们自己转换为File类。使用了MultipartFile工具类之后,我们对文件上传的操作就简便许多了。
1.Controller.class
/**
* Created on 2024/3/25.
*/
@RestController
@RequestMapping("/Upload")
public class UploadController {
private static Logger logger = LoggerFactory.getLogger(UploadController.class);
private final String[] sufix = {".doc", ".docx", ".xls", ".xlsx", ".pdf", ".jpg", ".png", ".mp4"};
@Autowired
UploadRepository uploadRepository;
@Value("${local-path}")
private String localPath;
// 文件上传、编辑
@PostMapping("/upload")
public ResponseObject uploadFile(HttpServletRequest request, @RequestParam MultipartFile files, UploadFile uploadFile) {
String id = null;
if(uploadFile.getId() == null){
id = UUID.randomUUID().toString();
} else {
id = uploadFile.getId();
}
String year = DateUtil.getCurrentYear();
FileOutputStream out = null;
try {
String fileName = files.getOriginalFilename();
if (fileName.indexOf("\\") != -1) {
fileName = fileName.substring(fileName.lastIndexOf("\\"));
}
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
// 文件保存路径
String type = "file";
String filePath = "";
uploadFile.setRealName(fileName);
uploadFile.setId(id);
uploadFile.setFileName(id + "." + suffix);
uploadFile.setSuffix(suffix);
uploadFile.setStatus("0");
uploadFile.setFileType(FileTypeUtil.getType(suffix).toString());
uploadFile.setUpDate(DateUtil.getDateTime());
// uploadFile.setCreateUserId(user.getUserId());
uploadFile.setCreateTime(DateUtil.getDateTime());
String relatPath = "";
if (uploadFile.getFolderName() != null) {
relatPath = "files/upload/" + year + "/" + type + "/" + uploadFile.getFolderName() + "/";
} else {
relatPath = "files/upload/" + year + "/" + type + "/";
}
filePath = localPath + relatPath + uploadFile.getFileName();
uploadFile.setPath(filePath);
File dest = new File(localPath + relatPath + uploadFile.getFileName());
uploadFile.setRelatPath(relatPath);
// 获取文件存放地址
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
// 文件保存到指定目录下
files.transferTo(dest);
// 文件信息保存到数据库
uploadRepository.save(uploadFile);
Map<String, Object> map = new HashMap<>();
map.put("id", uploadFile.getId());
map.put("fileType", uploadFile.getFileType());
map.put("realName", uploadFile.getRealName());
map.put("path", uploadFile.getRelatPath() + uploadFile.getFileName());
return ResponseObject.ok("上传成功", map);
} catch (Exception e) {
return ResponseObject.error("上传失败");
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 文件查询
@PostMapping("/getFileById")
public ResponseObject getFileById(@RequestBody UploadFile uploadFile) {
Optional<UploadFile> file = uploadRepository.findById(uploadFile.getId());
Map<String, Object> map = new HashMap<>();
map.put("id", file.get().getId());
map.put("fileType", file.get().getFileType());
map.put("realName", file.get().getRealName());
map.put("path", file.get().getRelatPath() + file.get().getFileName());
return ResponseObject.ok("文件查询成功", map);
}
// 文件删除
@PostMapping("/delFileById")
public ResponseObject delFileById(@RequestBody UploadFile uploadFile) {
Optional<UploadFile> upload = uploadRepository.findById(uploadFile.getId());
if(upload.isPresent()){
File file = new File(upload.get().getPath());
file.delete();
uploadRepository.deleteById(uploadFile.getId());
return ResponseObject.ok("文件删除成功!");
} else {
return ResponseObject.ok("文件未找到!");
}
}
}
2.application.yml
添加文件保存的绝对路径:
# 文件上传路径
localPath: "D:/file/"
3.WebMvcConfig.class
添加文件路径配置,可以访问到文件:
/**
* Created on 2023/2/27.
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Value("${localPath}")
private String localPath;
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };
@Override
public void addResourceHandlers(ResourceHandlerRegistry handlerRegistry) {
handlerRegistry.addResourceHandler("/static/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
handlerRegistry.addResourceHandler("/files/**").addResourceLocations("file:"+localPath+"files\\");
super.addResourceHandlers(handlerRegistry);
handlerRegistry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
super.addResourceHandlers(handlerRegistry);
}
}