【開發心得】Sring boot 獲取資源文件

 

在讀取springBoot構建的項目時,如果使用傳統的FileInputStream讀取文件流或者ResourceUtils工具類的方式

File file= ResourceUtils.getFile("classpath:test.xlsx");   

可能會出現File is not found的問題。

在springboot中可以使用ClassPathResource獲取文件流的方式方便下載文件

try {
    ClassPathResource classPathResource = new ClassPathResource("test.xlsx");
    File file = classPathResource.getFile();
    InputStream inputStream = classPathResource.getInputStream();
      //輸出文件
    InputStream fis = new BufferedInputStream(inputStream);
    byte[] buffer = new byte[fis.available()];
    fis.read(buffer);
    fis.close();
    response.reset();

    //獲取文件的名字再瀏覽器下載頁面
    String name = file.getName();
    response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), "iso-8859-1"));
    response.addHeader("Content-Length", "" + file.length());
    OutputStream out = new BufferedOutputStream(response.getOutputStream());
    response.setContentType("application/octet-stream");
    out.write(buffer);
    out.flush();
    out.close();
} catch (Exception e) {
    e.printStackTrace();
}

最後就是瀏覽器訪問接口下載文件了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章