springboot導入數據的時候,爲了方便用戶下載模板,會在項目資源目錄底下放模板。當項目用開發工具時,以下代碼可以正常下載文件
FileDownLoadUtil.download(this.getClass().getResource("excel").getPath()
+"/"+"文件名.xlsx",response,true);
/**
* 文件下載接口
* @param response
* @param isOnLine 傳入true,表示打開,但是打開的是瀏覽器能識別的文件,比如圖片、pdf,word等無法打開
* 傳入false,只是下載,如果不傳入這個參數默認爲false
* @throws Exception
*/
@Deprecated
public static void download(String filePath, HttpServletResponse response,boolean isOnLine)throws Exception{
File f = new File(filePath);
if (!f.exists()) {
response.sendError(1, "File not found!");
return;
}
String fileName = f.getName().replace("1","").replace("2","");
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
response.reset(); // 非常重要
if (isOnLine) { // 在線打開方式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + fileName);
// 文件名應該編碼成UTF-8
} else { // 純下載方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}
但是項目打包運行的時候,卻報錯FileNotFoundException
!!!因爲壓縮包是一個文件,不是一個文件夾,獲取到路徑並不是實際的路徑,所以應該以流的形式,去獲取內容
public static void download(InputStream is, HttpServletResponse response, String fileName)throws Exception{
if (is == null) {
response.sendError(1, "File not found!");
return;
}
fileName = fileName.replace("1","").replace("2","");
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
BufferedInputStream br = new BufferedInputStream(is);
byte[] buf = new byte[1024];
int len = 0;
response.reset(); // 非常重要
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}