@RequestMapping("/imgUpload")
@ResponseBody
public BaseResponse imgUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req, @RequestParam("g_id") Integer g_id) {
String path = req.getServletContext().getRealPath("/images/product");
File realPath = new File(path);
if (!realPath.exists() && !realPath.mkdirs()) {
return new BaseResponse<>(500, "无法创建目录", "");
}
String currentName = System.currentTimeMillis() + "_" + file.getOriginalFilename(); // 添加下划线分隔时间戳和原始文件名
String href = "/images/product/" + currentName;
try {
// 先尝试更新数据库
goodsService.setimgUrl(href, g_id);
// 数据库更新成功,继续保存文件
File destinationFile = new File(realPath, currentName);
file.transferTo(destinationFile); // 尝试保存文件
// 文件保存成功,返回成功响应
return new BaseResponse<>(0, "上传成功", href);
} catch (IOException e) {
e.printStackTrace();
return new BaseResponse<>(500, "上传失败:" + e.getMessage(), "");
} catch (Exception e) {
e.printStackTrace();
return new BaseResponse<>(500, "数据库更新失败:" + e.getMessage(), "");
}
}
本想将上传后的图片加入到src/main/resources/static/images/product下。但是以上代码测试后发现保存到了C:\Users\DBYT\AppData\Local\Temp中。
将代码改为
String absolutePath = "C:/Users/DBYT/IdeaProjects/springboot_demo/src/main/resources/static/images/product";
File realPath = new File(absolutePath);
成功保存到指定的目录下
req.getServletContext().getRealPath("/images/product")解析出的路径是相对于部署的Spring Boot应用的上下文路径,而不是文件系统的绝对路径。在开发环境中,这可能指向项目的target或build目录下的一个临时位置,而不是src/main/resources/static目录。