前言:目前大三,自己也在學習和摸索的階段。在和學校的同學一起做前后端分離項目的時候,我們發現將后端打包成jar,然后部署到服務器中通過java -jar xxx.jar運行項目以后,項目中存在文件上傳的接口(上傳位置在項目resources/static下)上傳文件以后前端竟然無法訪問顯示!而我自己在我的本機電腦啟動項目則沒有任何的問題???在網上找了很多的經驗發現沒有能夠解決我的問題的,經過不斷地調試試錯,終於解決了,發布出來記錄一下踩坑經歷,也希望能夠幫助到遇見同樣問題的朋友們。
說明:java項目打包成為jar包以后,在linux服務器上通過java -jar命令運行。linux是無法解壓jar包的,也就是無法訪問到resources/static里面存放的靜態圖片。jar包只能用於跑代碼!
解決方案:在linux文件夾jar包存在的同級目錄中創建文件上傳的文件夾,並更改文件上傳的路徑。如圖所示

程序內部文件上傳的路徑為:

配置類配置映射器:
import cn.hongyuan.handler.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.*; @Configuration public class MyWebConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //獲取文件的真實路徑 work_project代表項目工程名 需要更改 String os = System.getProperty("os.name"); String path2 = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\images\\avatar\\"; if (os.toLowerCase().startsWith("win")) { String path = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\uploads\\"; registry.addResourceHandler("/uploads/**"). addResourceLocations("file:" + path); registry.addResourceHandler("/images/avatar/**") .addResourceLocations("file:"+path2); }else {//linux和mac系統 可以根據邏輯再做處理 ; registry.addResourceHandler("/uploads/**"). addResourceLocations("file:" + System.getProperty("user.dir") + System.getProperty("file.separator") + "uploads"+ System.getProperty("file.separator")); registry.addResourceHandler("/images/avatar/**"). addResourceLocations("file:" + System.getProperty("user.dir") + System.getProperty("file.separator") + "images" + System.getProperty("file.separator") + "avatar" + System.getProperty("file.separator")); } registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); }
配置文件配置靜態資源放行路徑:
spring.resources.static-locations=classpath:/static,classpath:/resources,file:/home/xinyou/uploads/,file:/home/xinyou/images/avatar/
至此,大功告成!
ps: 我之前的文件上傳書寫方式也是在網上查詢的一些代碼,上傳文件的路徑多在windows環境下,確實沒有任何問題,但是一部署到linux就出現問題了,還是由於自己對linux服務器不夠熟悉所造成的,在今后的學習生活中還應該不斷地保持學習態度,如果有任何錯誤的地方也歡迎大家批評改正,一起進步!
