vue前端代码如下
1.1js代码
export function downloadExcelFile (params) {
return request({
url: 'api/channel/downloadExcelFile',
method: 'get',
responseType: 'blob',
params: params
})
1.1vue引用
download (file) {
let param = {
'pdfPatch': file.url
}
api.downloadExcelFile(param).then(res => {
var fileName = file.name
const blob = new Blob([res])
if ('download' in document.createElement('a')) { // 非IE下载
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
} else { // IE10+下载
navigator.msSaveBlob(blob, fileName)
}
})
}
2.java接口代码
@RequestMapping(value = "/downloadExcelFile")
public void getFileInputStream(String pdfPatch, HttpServletRequest request,HttpServletResponse response) throws Exception {
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try {
File file = new File(pdfPatch);
FileInputStream fis = new FileInputStream(file);
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment;filename=" + file.getName());
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[2048];
int len;
while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, len);
bos.flush();
}
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
}
}