Spring-boot中獲取路徑(十二)


前言

Spring-boot中獲取路徑的一般方式

一、SpringBoot讀取Resource下文件的幾種方式

需求:提供接口下載resources目錄下的模板文件,(或者讀取resources下的文件)給后續批量導入數據提供模板文件。

方式一:ClassPathResource 

//獲取模板文件:注意此處需要配置pom.xml文件;因為spring-boot默認只會讀取application.yml配置文件
        ClassPathResource classPathResource = new ClassPathResource(examplePath);
        File file = null;
        try {
            file= classPathResource.getFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

模板文件位置

坑1:找不到模板文件staffTemplate.xlsx。
原因:maven默認只編譯默認配置文件格式的文件,如yml。
解決:pom.xml 增加下面配置

 <build>
      <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.xlsx</include>
                </includes>
            </resource>
        </resources>
    </build>

坑2:中文文件名下載后無法正常顯示。
解決:將中文編碼

將
response.setHeader("Content-Disposition", "attachment;fileName=批量上傳用戶模板.xlsx");
//String fileName=new String("批量上傳用戶模板".getBytes(), StandardCharsets.ISO_8859_1);
改為
response.setHeader("Content-Disposition", "attachment;fileName=" + new String("批量上傳用戶模板".getBytes(), StandardCharsets.ISO_8859_1)
                    + ".xlsx");

參考鏈接:https://blog.csdn.net/weixin_42410936/article/details/106126377

問題:我通過這種方式,在本地可以找到路徑,升到測試環境就不可以了。

二、ResourceUtils的用法

搜索關鍵詞:

ResourceUtils讀取properties文件  

ResourceUtils.getURL()用法及實例

參看鏈接:

https://www.cnblogs.com/qlqwjy/p/7530715.html 

https://www.cnblogs.com/szrs/p/15207672.html

 


免責聲明!

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



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