一、 下载方式
a) 获取后端传过来的url 静态资源
-
通过a标签做点击操作
-
Window.location.href = url下载
-
Window.open(url)下载
b) 文件流下载(application/json; application/octet-stream)
- 文件流获取转换blob对象模拟a标签点击下载
二、 下载doc文件流示例
a) 后端主要代码
b) 前端主要代码
- Axios Api请求如下:
export const reportDownload = row => {
return request({
url: '/api/diagnose/download/'+ row.id + '/' + row.filetype ,
method: 'get',
responseType: "blob",
headers: {
'Content-Type': 'application/json; application/octet-stream'
},
data: row
})
};
-
response数据如下:
-
获取数据并模拟a标签点击:
const blob = new Blob([res.request.response], {type: 'application/msword'});
const fileName = decodeURI(res.headers['content-disposition'].split('=')[1]) +".doc";
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);
}
三、 文件流下载关键点说明
a) 后端
- 设置字符集和文件后缀名
response.setContentType("application/msword;" + "charset = UTF-8");
- 设置文件名称,这里encode必须设置,前端decodeURI解析,否则中文乱码
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(diagnoseReport.getName(), "UTF-8"));
- 设置response字符集
response.setCharacterEncoding("UTF-8");
b) 前端
- Ajax请求api中的response类型必须添加(因为response回传不存在blob类型,默认字符串,会导致下载的文件无法解析)
responseType: "blob"
- blob获取需要标注文件类型
new Blob([res.request.response], {type: 'application/msword'});
- 获取文件名字,用decodeURI解码
decodeURI(res.headers['content-disposition'].split('=')[1]) +".doc";