spring 上传图片

时间:2021-07-20 20:58:20
 @RequestMapping(value = "/upload",method = RequestMethod.POST)
public String upload(@RequestParam(value = "file", required = false) MultipartFile file){
// 判断文件是否为空
if (!file.isEmpty()) {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"+ file.getOriginalFilename(); UUID uuid = UUID.randomUUID(); String filename = uuid + file.getOriginalFilename();
File targetFile = new File(filePath,filename);
if (!targetFile.exists()) { try {
targetFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// 转存文件
try {
file.transferTo(targetFile);
} catch (IOException e) {
e.printStackTrace();
} }
return "upload";
}