一、概述
文件下載是比較常用的一種功能,尤其是在excel下載,更是比較常用的。每次遇到下載功能,我也就a標籤或者是form標籤進行下載,a標籤呢基本上就時只能get方式的下載,form可以get也可以post方式進行下載。但是這兩種方式都由一個確定就是無法設置header請求頭(目前我不知道怎麼設置請求頭),也就是說如果請求需要攜帶token之類的指令的時候使用這兩個標籤基本上就是廢了。所以異步下載就只能是使用文件流然後到前端進行轉換了。
二、a標籤下載
@GetMapping("/exportExcel")
public void exportExcel(HttpServletResponse response) throws IOException {
ServletOutputStream outputStream = response.getOutputStream();
InputStream is = new FileInputStream("F:/我的下載/test.xlsx");
IOUtils.copy(is,outputStream);
}
<a href="http://127.0.0.1:8080/exportExcel" download="test.xlsx">點擊下載</a>
後端配合文件輸出流很容易就可以進行下載,可以說a標籤下載時最方便的。
三、form標籤下載
@GetMapping("/exportExcel")
public void exportExcel(HttpServletResponse response) throws IOException {
ServletOutputStream outputStream = response.getOutputStream();
InputStream is = new FileInputStream("F:/我的下載/test.xlsx");
IOUtils.copy(is,outputStream);
}
<form action="http://127.0.0.1:8080/exportExcel" method="get">
<!--<input type="text" name="sheetName" value="test">-->
<input type="submit" value="點擊下載">
</form>
後端也是隻要配合文件的輸出流就可以很容易的進行下載了。當然也可以寫方法的,只不過方法裏面時使用js寫了一個form標籤。
<button onClick="downloadFileByForm()">點擊下載</button>
function downloadFileByForm() {
var url = "http://127.0.0.1:8080/exportExcel";
// form是隱藏的不會顯示在頁面上
var form = $("<form style='display: none'></form>").attr("action", url).attr("method", "get");
// 添加到body下然後進行提交之後直接刪除掉這個標籤
form.appendTo('body').submit().remove();
};
四、ajax異步下載
ajax異步文件下載是最麻煩的,因爲,你請求成功之後,success方法裏面的數據msg是一串數據流,你需要將數據流轉換成文件進行下載,但是數據流轉文件的方法我也沒找到,所以網上給出的方法就是將接收到的數據變成前端一個地址,然後使用a標籤對這個地址進行下載。
/* 後端代碼 */
@GetMapping("/exportExcel")
public void exportExcel(HttpServletResponse response) throws IOException {
ServletOutputStream outputStream = response.getOutputStream();
InputStream is = new FileInputStream("F:/我的下載/test.xlsx");
IOUtils.copy(is,outputStream);
}
/* 前端代碼 */
<button onClick="downloadFileByAjax()">點擊下載</button>
function downloadFileByAjax() {
$.ajax({
type: "get",
url: "/exportExcel",
// 返回類型需要blob,blob表示數據流是文件數據
xhrFields: { responseType: "blob" },
success: function(msg){
// 將返回數據轉換爲地址
var url = window.URL.createObjectURL(new Blob([msg]))
// 創建a標籤
var link = document.createElement('a')
// a標籤隱藏
link.style.display = 'none'
// 把地址給a標籤
link.href = url
// 設置a標籤的下載屬性
link.setAttribute('download', 'excel.xlsx')
// 將a標籤添加到某個存在的標籤下
document.body.appendChild(link)
// a標籤點擊下載
link.click()
}
});
};