spring boot實現檔案的下載
在前端頁面,html中JavaScript指令碼的定義如下:
function exportFile(){
var form=$("<form>");
form.attr("style","display:none");
form.attr("target","");
form.attr("method","post");//提交方式為post
form.attr("action","/downloadFile");//定義action
$("body").append(form);
form.submit();
}
在Spring boot中的Controller類中建立一個方法downloadFile,方法體的定義如下:
@RequestMapping("/downloadFile")
private String downloadFile(HttpServletResponse response){
String downloadFilePath = "/root/fileSavePath/";//被下載的檔案在伺服器中的路徑,
String fileName = "demo.xml";//被下載檔案的名稱
File file = new File(downloadFilePath);
if (file.exists()) {
response.setContentType("application/force-download");// 設定強制下載不開啟
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream outputStream = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, i);
i = bis.read(buffer);
}
return "下載成功";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return "下載失敗";
}
在前端頁面點選“下載檔案”按鍵後,
會自動彈出下載檔案的對話方塊,效果圖如下: