直接上代码
后端代码:
@GetMapping(value = "/excel")
@ApiOperation(value = "模板下载", httpMethod = "GET")
public void download(HttpServletRequest request,HttpServletResponse response) {
try {
String path = importExcelModelFilePath + "外区转入函询数据导入模板.xlsx";
// CreateTxt.downLoadFile(path, response, false);
File file = new File(path);
if (!file.exists()) {
response.sendError(404, "File not found!");
} else {
// 取得文件名。
String filename = file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
// JSONP 解决跨域问题
response.reset();
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
// 设置response的Header
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(filename.getBytes(),"iso-8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
//http://www.ruanyifeng.com/blog/2016/04/cors.html 跨域详情介绍
toClient.write(buffer);
toClient.flush();
toClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
前端代码:
async download() {
let errorMsg
let blobStream = await download().catch((err) => {
console.log('exportExcelErr:', err)
errorMsg = err
})
debugger
if (blobStream.size === 0) {
this.$message.error('响应数据错误...' + errorMsg)
return
}
//this.streamDownload(blobStream, '默认文件.xlsx')
this.downloadFile(blobStream,'函询数据模板.xlsx')
},
// URL.createObjectURL() 静态方法会创建一个DOMString,其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的document绑定
downloadFile:function(data,fileName){
// data为blob格式
var blob = new Blob([data]);
var downloadElement = document.createElement('a');
var href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = fileName;
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
},