给前端传输流,然后下载下来
这里提供一个思路,可以借鉴参考一下,写的比较简单.
Java后端代码
public void extract(HttpServletResponse response) throws Exception{
File file = new File("D://abc.zip");
response.setContentType("application/octet-stream;charset=utf-8");
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(FileUtil.getName(file), "UTF-8"));
FileInputStream fileInputStream = new FileInputStream(file);
int len = 0;
byte[] buffer = new byte[1024];
OutputStream outputStream = response.getOutputStream();
while((len=fileInputStream.read(buffer))>0) {
outputStream.write(buffer, 0, len);
}
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
前端代码接受实现
axios({
method: 'post',
url: '/plat/document/configure/extract',
data: data,
responseType: 'blob',
headers: {
'Authorization': 'bearer ' + Cookies.get('vue_admin_template_token'),
'Content-Type': 'application/json'
},
}).then(res => {
console.log(res);
const blob = res.data;
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = (e) => {
const a = document.createElement('a');
a.download = res.headers.content-disposition.split('filename=')[1];
a.href = e.target.result;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
})