springboot配置虛擬路徑訪問上傳到磁盤的文件


問題描述:

文件上傳到磁盤后,如果想要訪問該文件的話,可以通過配置虛擬路徑映射到該磁盤文件進行訪問。

 

解決方法:

1、在application.properties文件中配置虛擬路徑,需要注意的是,"訪問文件的基本路徑地址"的IP地址和端口號必須和項目的相同

#磁盤文件存儲路徑
file.path=H:/Business/image/

#虛擬路徑
file.static-path=/upload/image/**

#訪問文件的基本路徑地址
file.base-url=http://127.0.0.1:8080/upload/image/

 

2、編寫虛擬路徑配置

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.WebMvcConfigurer;
/**
 * 虛擬路徑配置類
 */
@Configuration
public class WebAppMvcConfig implements WebMvcConfigurer {
    @Value("${file.path}")
    private String path;

    @Value("${file.static-path}")
    private String staticPath;
    
    // 如果訪問http://localhost:8080/upload/image/test.jpg
    // 實則訪問H:/Business/image/test.jpg
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {  
registry.addResourceHandler(staticPath).addResourceLocations("file:"+path);
} }

 


免責聲明!

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



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