前端代码
xaizai(){
axios({
method: "GET",
url: url,
responseType:'blob',
}).then(response => {
console.log(response)
this.download(response)
})
},
download (res) {
let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
const blobURL = window.URL.createObjectURL(blob)
const tempLink = document.createElement('a')
tempLink.style.display = 'none'
tempLink.href = blobURL
tempLink.setAttribute('download', decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]))
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank')
}
document.body.appendChild(tempLink)
tempLink.click()
document.body.removeChild(tempLink)
window.URL.revokeObjectURL(blobURL)
}
后端代码
@GetMapping("/download")
public void getFile(HttpServletResponse response) throws Exception{
File readFile = new File(System.getProperty("user.dir") + File.separator + "物流用户信息导入模板.xlsx");
FileInputStream fileInputStream = new FileInputStream(readFile);
response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("物流用户信息导入模板.xlsx","utf-8"));
ServletOutputStream outputStream = response.getOutputStream();
byte[] bytes = new byte[1024*10];
int read;
do {
read = fileInputStream.read(bytes);
outputStream.write(bytes,0,read);
}while (-1 != read);
IOUtils.closeQuietly(fileInputStream);
IOUtils.closeQuietly(outputStream);
}
亲测可以使用,如果写后端直接复制后端,如果写前端直接复制前端,有问题可以评论找我