天天看點

springboot、springcloud之靜态資源路徑的配置 靜态資源路徑是指系統可以直接通路的路徑,且路徑下的所有檔案均可被使用者直接讀取。 轉載位址:http://blog.csdn.net/kilua_way/article/details/54601195

靜态資源路徑是指系統可以直接通路的路徑,且路徑下的所有檔案均可被使用者直接讀取。

在Springboot中預設的靜态資源路徑有:

classpath:/METAINF/resources/

classpath:/resources/

classpath:/static/

classpath:/public/

,從這裡可以看出這裡的靜态資源路徑都是在

classpath

中(也就是在項目路徑下指定的這幾個檔案夾)

試想這樣一種情況:一個網站有檔案上傳檔案的功能,如果被上傳的檔案放在上述的那些檔案夾中會有怎樣的後果?

  • 網站資料與程式代碼不能有效分離;
  • 當項目被打包成一個

    .jar

    檔案部署時,再将上傳的檔案放到這個

    .jar

    檔案中是有多麼低的效率;
  • 網站資料的備份将會很痛苦。

此時可能最佳的解決辦法是将靜态資源路徑設定到磁盤的基本個目錄。

在Springboot中可以直接在配置檔案中覆寫預設的靜态資源路徑的配置資訊:

  • application.properties

    配置檔案如下:
server.port=

web.upload-path=D:/temp/study13/

spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
  classpath:/static/,classpath:/public/,file:${web.upload-path}
           

注意:

web.upload-path

這個屬于自定義的屬性,指定了一個路徑,注意要以

/

結尾;

spring.mvc.static-path-pattern=/**

表示所有的通路都經過靜态資源路徑;

spring.resources.static-locations

在這裡配置靜态資源路徑,前面說了這裡的配置是覆寫預設配置,是以需要将預設的也加上否則

static

public

等這些路徑将不能被當作靜态資源路徑,在這個最末尾的

file:${web.upload-path}

之所有要加

file:

是因為指定的是一個具體的硬碟路徑,其他的使用

classpath

指的是系統環境變量

  • 編寫測試類上傳檔案
package com.zslin;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.FileCopyUtils;

import java.io.File;

/**
 * Created by 鐘述林 [email protected] on 2016/10/24 0:44.
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class FileTest {

    @Value("${web.upload-path}")
    private String path;

    /** 檔案上傳測試 */
    @Test
    public void uploadTest() throws Exception {
        File f = new File("D:/pic.jpg");
        FileCopyUtils.copy(f, new File(path+"/1.jpg"));
    }
}                

注意:這裡将

D:/pic.jpg

上傳到配置的靜态資源路徑下,下面再寫一個測試方法來周遊此路徑下的所有檔案。

@Test
public void listFilesTest() {
    File file = new File(path);
    for(File f : file.listFiles()) {
        System.out.println("fileName : "+f.getName());
    }
}                

可以到得結果:

說明檔案已上傳成功,靜态資源路徑也配置成功。

  • 浏覽器方式驗證

由于前面已經在靜态資源路徑中上傳了一個名為

1.jpg

的圖檔,也使用

server.port=1122

設定了端口号為

1122

,是以可以通過浏覽器打開:

http://localhost:1122/1.jpg

通路到剛剛上傳的圖檔。

轉載位址:http://blog.csdn.net/kilua_way/article/details/54601195

繼續閱讀