前言
最近項目將token信息放在請求的header中,所以不可以用iframe的src屬性下載文件,因爲不可以操作請求頭。這裏記錄一下使用axios實現文件下載的方法。
具體實現
- 前端代碼
axios({
method: 'post',
url: 'export/download/',
data: {
id: fileId
},
headers: {
'Content-Type': 'application/json',
'token': localStorage.getItem('token')
},
responseType: 'blob'
}).then(res => {
const href = window.URl.createObjectURL(new Blob([res.data])) // 創建下載鏈接
const a = document.createElement('a')
a.style.display = 'none'
a.href = href
a.setAttribute('download', '123.txt')
document.body.appendChild(a)
a.click() // 下載點擊
document.body.removeChild(a) // 下載完成移除元素
window.URL.revokeObjectURL(href) // 釋放blob對象
})
- 後端代碼
@RequestMapping(value = "/download", method = RequestMethod.POST)
public void download(@RequestBody Map<String, Object> param, HttpServletRequest req, HttpServletResponse resp) {
String fileId = (String) param.get("id");
File file = new File("....." + fileId);
.........
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
try {
bis = new BufferedImputStream(new FileInputStream(file));
fos = resp.getOutputStream();
bos = new BufferedOutputStream(fos);
.......
setHeader等等操作
......
resp.setContentType("application/octet-stream");
int byteRead = 0;
byte[] buffer = new byte[8192];
while ((byteRead = bis.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, byteRead);
}
} catch(Exception e) {
} finally {
try {
bos.flush();
bis.close();
fos.close();
bos.close();
file.delete();
} catch {
}
}
}
注意事項
1.前端代碼中,responseType: 'blob'
很重要。
2.前端代碼中,向後臺傳參用的json,所以headers
的Content-Type
中用application/json
,相應後臺用@RequestBody Map<String, Object> param
接收參數。
3.後臺代碼中resp.setContentType("application/octet-stream");
很重要。
4.後臺下載的文件格式可以爲txt,pdf,csv等,相應前臺文件名也要以這些結尾。