spring boot对外部文件的访问
生活随笔
收集整理的這篇文章主要介紹了
spring boot对外部文件的访问
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
很多朋友都會遇到這個問題,項目打包成jar格式,本地其他盤符里面的文件訪問不到(項目達(dá)成war包的和資源是在服務(wù)器訪問的請忽視),這里只需要在配置文件中添加配置,然后使用建立一個WebMvcConfigurerAdapter攔截就可以了
首先 application.properties配置文件中添加如下配置
#通過瀏覽器訪問文件的路徑 file.staticAccessPath=/api/file/** #本地資源路徑 file.uploadFolder=d:///uploadFile/ #file.uploadFolder=/root/laboratory/uploadfile/然后新建一個配置類
package com.xxx.xxx;import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; //import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configuration public class UploadFilePathConfig extends WebMvcConfigurationSupport{@Value("${file.staticAccessPath}")private String staticAccessPath;@Value("${file.uploadFolder}")private String uploadFolder;@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {//外部文件registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);//內(nèi)部靜態(tài)文件(使用WebMvcConfigurationSupport之后內(nèi)部靜態(tài)文件無法訪問的話就添加以下這段代碼)registry.addResourceHandler("/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/"); }}經(jīng)過以上兩步配置之后,啟動項目,訪問http://localhost:80xx/api/file/123.jpg ,便可以訪問123.jpg文件了
總結(jié)
以上是生活随笔為你收集整理的spring boot对外部文件的访问的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 无失真传输
- 下一篇: JVM运行参数之-X和-XX参数