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

 

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