js下载url文件
需求
后台返回文件的URL,前端自动下载
实现
function download(url, filename){
const elelink = document.createElement("a");
elelink.style.display = 'none';
elelink.download = filename;
elelink.href = url;
document.body.appendChild(elelink);
elelink.click();
document.body.removeChild(elelink);
}
遇到的问题
当下载文件是txt格式时,浏览器会自动打开。
解决方法一:在服务器后台nginx配置http请求头
server {
listen 8080;
location ~ /group([0-9])/M00 {
if ($request_filename ~* ^.*?.(txt|doc|pdf|rar|gz|zip|docx|exe|xlsx|ppt|pptx)$){
add_header Content-Disposition attachment;
}
root /opt/fastdfs;
ngx_fastdfs_module;
}
}
解决方法二:下载文件并保存到本地
// 保存到本地并自动点击
function saveAs(data, name) {
const urlObject = window.URL || window.webkitURL || window;
const export_blob = new Blob([data]);
const save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = urlObject.createObjectURL(export_blob);
save_link.download = name;
save_link.click();
}
// 下载含有url的文件
function downloadUrlFile(url, fileName) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
//xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
// 为了避免大文件影响用户体验,建议加loading
xhr.onload = () => {
if (xhr.status === 200) {
// 获取文件blob数据并保存
saveAs(xhr.response, fileName);
}
};
xhr.send();
}
downloadUrlFile(url, fileName);
文件type类型
后缀 | MIME Type |
---|---|
.doc | application/msword |
.docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.xls | application/vnd.ms-excel |
.xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.ppt | application/vnd.ms-powerpoint |
.pptx | application/vnd.openxmlformats-officedocument.presentationml.presentation |
本文参考文章:
https://www.cnblogs.com/huchong-bk/p/11846927.html
还没有评论,来说两句吧...