springboot-為內置tomcat設置虛擬目錄


需求

項目使用springboot開發,以jar包方式部署。項目中文件上傳均保存到D判斷下的upload目錄下。

在瀏覽器中輸入http://localhost:8080/upload/logo_1.jpg能訪問到D盤upload目錄下的logo_1.png圖片

 

 

解決方法

由於使用jar包方式,無法使用為tomcat配置虛擬目錄的方式,需為springboot內置tomcat設置虛擬目錄。

 

實現

 

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/upload/");       
    }

}

 

啟動項目,在瀏覽器中輸入http://localhost:8080/upload/logo_1.jpg,即可正常訪問圖片了。

 

上面的例子中攔截器攔截的請求和文件上傳目錄均是寫死的,可將其放置application.properties配置文件 中, 便於修改。修改后代碼如下所示:

 

application.properties

server.port=8080

#靜態資源對外暴露的訪問路徑
file.staticAccessPath=/upload/**
#文件上傳目錄
file.uploadFolder=D:\\upload

 

FileUploadProperteis.java

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 文件上傳相關屬性
 * @create 2018-04-22 13:58
 **/
@Component
@ConfigurationProperties(prefix = "file")
public class FileUploadProperteis {

    //靜態資源對外暴露的訪問路徑
    private String staticAccessPath;

    //文件上傳目錄
    private String uploadFolder ;

    public String getStaticAccessPath() {
        return staticAccessPath;
    }

    public void setStaticAccessPath(String staticAccessPath) {
        this.staticAccessPath = staticAccessPath;
    }

    public String getUploadFolder() {
        return uploadFolder;
    }

    public void setUploadFolder(String uploadFolder) {
        this.uploadFolder = uploadFolder;
    }
}

 

WebMvcConfig.java

import com.lnjecit.springboothelloworld.properties.FileUploadProperteis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private FileUploadProperteis fileUploadProperteis;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(fileUploadProperteis.getStaticAccessPath()).addResourceLocations("file:" + fileUploadProperteis.getUploadFolder() + "/");       
    }

}

 

demo下載地址:https://github.com/linj6/springboot-learn/tree/master/springboot-helloworld

 

參考資料

1、https://liuyanzhao.com/7599.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM