admin管理员组

文章数量:1559079

!!!总是碰到下载文件的需求,在这里统一整理一下方法

 

一、此方法火狐有些版本是不支持的

window.location.href = 'https://*****.oss-cn-**.aliyuncs/*********';

二、为了解决火狐有些版本不支持,可以改成这种方式

window.location='https://*****.oss-cn-**.aliyuncs/*********';

三、该方法ie和火狐都可以,url表示要下载的文件路径:

function(url){
    try {
          var elemif = document.createelement("iframe");
          elemif.src = url;
          elemif.style.display = "none";
          document.body.appendchild(elemif);
        } catch (e) {
          alert("下载异常!");
        }
}

四、form表单的形式

downloadfile(url){
      var form=$("
"); form.attr("style","display:none"); form.attr("target",""); form.attr("method","get"); form.attr("action",url); $("body").append(form); form.submit();//表单提交} }

五、a标签的方式

function(url,name){
    var a = document.createelement("a");
     a.download = name   ".xls";
     a.href = url;
     $("body").append(a); // 修复firefox中无法触发click
     a.click();
     $(a).remove();
}

六、假如后台给的文件流

function (formdata, url, name) {
  return new promise((resolve, reject) => {
    var xhr = new xmlhttprequest();
    xhr.open("post", url, true); // 也可以使用post方式,根据接口
    xhr.responsetype = "blob"; // 返回类型blob
    // 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
    xhr.onload = function () {
      // 请求完成
      if (this.status === 200) {
        // 返回200
        var blob = this.response;
        var reader = new filereader();
        reader.readasdata; // 转换为base64,可以直接放入a表情href
        reader.onload = function (e) {
          // 转换完成,创建一个a标签用于下载
          var a = document.createelement("a");
          a.download = name   ".xls";
          a.href = e.target.result;
          $("body").append(a); // 修复firefox中无法触发click
          a.click();
          resolve(200)
          $(a).remove();
        };
      }
    };
    // 发送ajax请求
    xhr.send(formdata);
  })
};

七、download.js

我粘贴一下download的源码

//download.js v4.2, by dandavis; 2008-2016. [ccby2] see http://danml/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/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

用法:

download(fileurl,name,"video/mp4");

具体更多的用法请参考九游会真人第一品牌官网,

注意 download.js第一个参数 是数据流,不是像oss那样的文件地址

本文标签: 方法