js下载url文件
需求
后臺返回文件的URL,前端自動下載
實現
function download(url, filename){const elelink = document.createElement("a");elelink.style.display = 'none';elelink.target = '_blank';elelink.href = url;elelink.download = filename;document.body.appendChild(elelink);elelink.click();document.body.removeChild(elelink);}實現二
//直接將url賦值 window.location.href= url;javascript中window.open()與window.location.href的區別
window.open(“index.aspx”,‘top’); 只是表示打開這個頁面,并不是打開并刷新index.aspx
window.location.href=“index.aspx”; 表示重新定向到新頁面,同時刷新打開的這個頁面;
遇到的問題
當下載文件是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;} }解決方法二:下載文件并保存到本地
handleDownload = (url,filename) => {const x = new window.XMLHttpRequest();x.open('GET', url, true);x.responseType = 'blob';x.onload = () => {let time = new Date().toLocaleDateString();const url = window.URL.createObjectURL(x.response);const a = document.createElement('a');a.href = url;a.download = filename + "_" + time + '.txt';a.click();};x.send(); }使用href 的下載地址 和 當前網站地址 必須是 同源的,否則download不生效。如果不同源,使用解決方法二下載即可。
文件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
總結
- 上一篇: 超级简单java企业人力资源管理系统设计
- 下一篇: 路由器To路由器:双路由器连接设置