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文件就不用重新打包了。如何分目录,可以看我的另我一篇博客。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章