springboot图片或文件上传优雅解决方案,拒绝临时目录,太恶心。

           今天代码写到了头像上传,一上传就会把图片上传到D:\UserService\deployer\tomcat\work\Tomcat\localhost\ROOT\file:D:\UserService\config\image\portrait\1.png这个目录下面,并且出错。我指定的是D:\UserService\config\image\portrait\下面,为什么会增加了D:\UserService\deployer\tomcat\work\Tomcat\localhost\ROOT\?

          配置文件aplication.properties目录配置为:

     server.tomcat.basedir=deployer/tomcat
     portrait.path=file:D:/UserService/config/image/portrait/

代码为:

public UserResult uploadPortrait(long userId, MultipartFile portraitFile)
{
    UserResult userResult = new UserResult();

    if (userId == 0 || portraitFile.isEmpty())
    {
        LOGGER.error("Paramters is error");
        return userResult.retInvalidParamUserResult();
    }

    String originalFilename = portraitFile.getOriginalFilename();
    String exName = originalFilename.substring(originalFilename.lastIndexOf("."));
    String fileName = String.valueOf(userId) + exName;

    LOGGER.info("Picture name is : {}", fileName);

    try
    {    //PORTRAIT_FILT_PATH 为 file:D:/UserService/config/image/portrait/
         //路径由初始脚本创建,所以无需再进行校验。
        portraitFile.transferTo(new File(PORTRAIT_FILT_PATH + fileName));
    }
    catch (Exception e)
    {
        LOGGER.error("Save portrait fail. {}", e);
        return userResult.getUserResult(ErrorCode.USER_SAVE_PORTRAIT_FAIL.getMsg_id(),         ErrorCode.USER_SAVE_PORTRAIT_FAIL.getMsg(), null); 
    }

            POSTMAN调用,一直显示保存文件失败。经过分析发现,路径:file:D:/UserService/config/image/portrait/, 上传文件时()仅在上传文件时,增加了"file:"前缀后,springboot做特殊的处理,就是会增加tomcat目录默认目录。去掉"file:"前缀后,springboot不再做特殊处理,而使用真实的路径,保存可以成功。

补充一下springboot路径问题:

前缀"file:"指的是电脑的文件系统路径,可以是绝对路径,可以是相对路径。

前缀“classpath:”指的是resources目录,一般打包时会打到JAR包内。

个人建议,配置文件,mapper不要放到resources目录下,自己指定目录。如我司平台的目录如下(application.properties文件在config目录下):

这样的话,你修改配置,修改mapper.xml文件就不用重新打包了。如何分目录,可以看我的另我一篇博客。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值