springboot中开发环境下图片上传到Temp中的情况。

@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目录。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值