js文件下载替换文件名,vue下载文件替换文件名
下载文件方法
1、window.open和window.location.href
a,window.open()在下载文件的时候会打开一个新的页面,同时会暴露链接地址, 而且会在下载文件的过程中,访问链接2次,虽然前端只下载了一次文件,但是服务端会生成2次文件。
b,对于rar.doc.等浏览器不能打开的文件,使用window.location.href是完全可以实现下载的。
示例: window.location.href="http://下载.rar" ,等同于<a href="http://下载.rar">下载</a>
c,对于浏览器能打开得文件,例如html,xml,txt等,这样去写就不是下载,而是打开。我们想下载得话就得使用如下方法,
2.form表单
用动态生成的form元素,实现表单提交,并完成下载。注意此处不会ajax。原理仅仅是表单的提交。
由于jQery的ajax函数、及ajaxSubmit等函数的返回类型(dataType),只有xml、text、json、html等类型,没有’流’类型,故我们只要实现ajax下载时,不能够使用相应的ajax函数进行文件下载。
不过我们可以通过js生成一个form,用这个form提交参数,并返回“流”,类型数据。在实现过程中,页面也没有刷新
a标签(兼容性比较差,chrome没问题)
<a href="#"></a>
或者
let ipUrl = 'http://' + this.user.ip + ':' + msgUrl;
let a = document.createElement('a');
//
a.setAttribute('download', '');
a.href = ipUrl;
a.click();
document.body.removeChild(a); // 下载完成移除元素
iframe
如果是get方式的url下载链接,客户端可以通过一个动态生成的隐藏的iframe来得到下载的二进制文件。原理:iframe有一个src属性,其本质就是发送http请求,get页面或者数据。
down(){
try{
let iframeRequest = document.createElement('iframe');
iframeRequest.id = "IFrameReauest";
iframeRequest.src = ipUrl;
iframeRequest.style.display = "none";
document.body.appendChild(iframeRequest);
}catch{
console.log('下载异常');
}
}
插件download.js(具体请看官网:http://danml.com/download.html)
安装
npm install downloadjs --save
引入
import download from ‘downloadjs’ 引入
最后通过download()方法使用
下载调用的方法download(data, strFileName, strMimeType)对应为:download(“数据”,“想要起的名称”,“Mime类型”),当不写后面的两个参数时,就可以下载指定文件了(不支持跨域),源码很简单就是没有后面的参数,就会通过ajax发送一个get请求,获取url的二进制流,然后把二进制流转化为对象就完成了下载工作。
这里传入文件名,即可修改下载的文件名
插件源码
如果需要对文件进行其他限制,可以在文件限制
//download.js v4.2, by dandavis; 2008-2016. [CCBY2] see http://danml.com/download.html for tests/usage
// v1 landed a FF+Chrome compat way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
// v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
// v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.
// v4 adds AMD/UMD, commonJS, and plain browser support
// v4.1 adds url download capability via solo URL argument (same domain/CORS only)
// v4.2 adds semantic variable names, long (over 2MB) dataURL support, and hidden by default temp anchors
// https://github.com/rndme/download
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.download = factory();
}
}(this, function () {
return function download(data, strFileName, strMimeType) {
var self = window, // this script is only for browsers anyway...
defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
mimeType = strMimeType || defaultMime,
payload = data,
url = !strFileName && !strMimeType && payload,
anchor = document.createElement("a"),
toString = function(a){return String(a);},
myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
fileName = strFileName || "download",
blob,
reader;
myBlob= myBlob.call ? myBlob.bind(self) : Blob ;
if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
payload=[payload, mimeType];
mimeType=payload[0];
payload=payload[1];
}
if(url && url.length< 2048){ // if no filename and no mime, assume a url was passed as the only argument
fileName = url.split("/").pop().split("?")[0];
anchor.href = url; // assign href prop to temp anchor
if(anchor.href.indexOf(url) !== -1){ // if the browser determines that it's a potentially valid url path:
var ajax=new XMLHttpRequest();
ajax.open( "GET", url, true);
ajax.responseType = 'blob';
ajax.onload= function(e){
download(e.target.response, fileName, defaultMime);
};
setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return:
return ajax;
} // end if valid url?
} // end if url?
//go ahead and download dataURLs right away
if(/^data\:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)){
if(payload.length > (1024*1024*1.999) && myBlob !== toString ){
payload=dataUrlToBlob(payload);
mimeType=payload.type || defaultMime;
}else{
return navigator.msSaveBlob ? // IE10 can't do a[download], only Blobs:
navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
saver(payload) ; // everyone else can save dataURLs un-processed
}
}//end if dataURL passed?
blob = payload instanceof myBlob ?
payload :
new myBlob([payload], {type: mimeType}) ;
function dataUrlToBlob(strUrl) {
var parts= strUrl.split(/[:;,]/),
type= parts[1],
decoder= parts[2] == "base64" ? atob : decodeURIComponent,
binData= decoder( parts.pop() ),
mx= binData.length,
i= 0,
uiArr= new Uint8Array(mx);
for(i;i<mx;++i) uiArr[i]= binData.charCodeAt(i);
return new myBlob([uiArr], {type: type});
}
function saver(url, winMode){
if ('download' in anchor) { //html5 A[download]
anchor.href = url;
anchor.setAttribute("download", fileName);
anchor.className = "download-js-link";
anchor.innerHTML = "downloading...";
anchor.style.display = "none";
document.body.appendChild(anchor);
setTimeout(function() {
anchor.click();
document.body.removeChild(anchor);
if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(anchor.href);}, 250 );}
}, 66);
return true;
}
// handle non-a[download] safari as best we can:
if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
url=url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
if(!window.open(url)){ // popup blocked, offer direct download:
if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){ location.href=url; }
}
return true;
}
//do iframe dataURL download (old ch+FF):
var f = document.createElement("iframe");
document.body.appendChild(f);
if(!winMode){ // force a mime that will download:
url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
}
f.src=url;
setTimeout(function(){ document.body.removeChild(f); }, 333);
}//end saver
if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
return navigator.msSaveBlob(blob, fileName);
}
if(self.URL){ // simple fast and modern way using Blob and URL:
saver(self.URL.createObjectURL(blob), true);
}else{
// handle non-Blob()+non-URL browsers:
if(typeof blob === "string" || blob.constructor===toString ){
try{
return saver( "data:" + mimeType + ";base64," + self.btoa(blob) );
}catch(y){
return saver( "data:" + mimeType + "," + encodeURIComponent(blob) );
}
}
// Blob but not URL support:
reader=new FileReader();
reader.onload=function(e){
saver(this.result);
};
reader.readAsDataURL(blob);
}
return true;
}; /* end download() */
}));
本文地址:https://blog.csdn.net/waillyer/article/details/109258811
上一篇: 数据结构:JS封装单、双向链表