js 點擊下載文件、圖片

想直接看結論,看代碼方法一!!!方法二和方法三不兼容,只是延伸下思路。

參考:
https://blog.csdn.net/weixin_33694620/article/details/88170573
https://www.jianshu.com/p/2af0610d82c7
https://www.zhangxinxu.com/wordpress/2017/07/js-text-string-download-as-html-json-file/
https://www.zhangxinxu.com/wordpress/2016/04/know-about-html-download-attribute/
http://danml.com/download.html

a標籤有一個download的屬性,添加了該屬性,a標籤將直接下載文件,並根據download屬性的值設置下載文件的文件名,不爲download屬性設置值則文件將以默認文件名下載:但是這個辦法有一個弊端,它僅支持同源鏈接下載,非同源鏈接還是會直接打開圖片

代碼:(非同源鏈接還是會直接打開圖片)

let aLink = document.createElement("a");
aLink.style.display = "none";
aLink.setAttribute('target', '_blank');
aLink.href = 'http://static.xuezhong100.com/uploadimg/20190627/49c328b56b81405c8ddcaf3fddb8a0b3.png';
aLink.download = 'picture.png';

document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);

改進版:(圖片轉爲Blob)

function downloadImg(url, name) {
  // 將鏈接地址字符內容轉變成blob地址
  fetch(url).then(function(res) {
  	res.blob();
  }).then(funtction(blob) {
    // 創建隱藏的可下載鏈接
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = URL.createObjectURL(blob);
    a.download = name;
    document.body.appendChild(a);
    a.click();
    // 移除元素
    document.body.removeChild(a);
  });
}
downloadImg('http://static.xuezhong100.com/uploadimg/20190627/49c328b56b81405c8ddcaf3fddb8a0b3.png', 'pic');

但是ie不支持fech,所以我們在改進一下


var x=new XMLHttpRequest();
var resourceUrl = "http://static.xuezhong100.com/uploadimg/20190627/49c328b56b81405c8ddcaf3fddb8a0b3.png";
x.open("GET", resourceUrl, true);
x.responseType = 'blob';
x.onload=function(e){
	var url = window.URL.createObjectURL(x.response)
	var a = document.createElement('a');
	a.href = url;
	a.download = '下載';
	a.click();
}
x.send();

ie10下載了,但是沒有自動加文件格式尾綴,ie11不支持a標籤的download屬性,判斷瀏覽器a標籤是否支持download屬性

var isSupportDownload = 'download' in document.createElement('a');

再次翻資料,找到這麼一段代碼:

// IE10+ : (has Blob, but not a[download] or URL)
if (navigator.msSaveBlob) {
    return navigator.msSaveBlob(blob, fileName);
}

整合一下,終極方法:

方法一:(Blob實現文件下載, 該方法各個文件格式都可以下載。ppt,doc,png,gif,兼容各個瀏覽器,ie10, ie10+)
PS: 如果有跨域問題,請找運營。的就是報cors跨域,他改了下配置文件就ok了

var x=new XMLHttpRequest();

//var resourceUrl = "http://static.xuezhong100.com/uploadfile/20190401/45549715ba2e428b8e415a30d9392c97.doc";
// var resourceUrl = 'http://static.xuezhong100.com/uploadfile/20190401/59a00a5259004f459f79a541dd05f1c3.pptx';
//var resourceUrl = "http://static.shuxuejia.com/img/201708020.gif";
var resourceUrl = "http://static.xuezhong100.com/uploadimg/20190627/49c328b56b81405c8ddcaf3fddb8a0b3.png";
x.open("GET", resourceUrl, true);
x.responseType = 'blob';

x.onload=function(e){
	// ie10+
	if (navigator.msSaveBlob) {
		var name = resourceUrl.substr(resourceUrl.lastIndexOf("/") + 1);
		return navigator.msSaveBlob(x.response, name);
	} else {
		var url = window.URL.createObjectURL(x.response)
		var a = document.createElement('a');
		a.href = url;
		a.download = '下載';
		a.click();
	}
}
x.send();

方法2和方法3我沒試過,copy過來的,提供一個引申方向。

方法二:(圖片base64,ie不支持)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

	</head>
	<body>
		<button onclick="download()">點擊下載</button>
	</body>
	<script>
		function download() {
			var image = new Image();
			image.crossOrigin = "anonymous";
			image.src = "http://is3.mzstatic.com/image/thumb/Music62/v4/4b/f6/a2/4bf6a267-5a59-be4f-6947-d803849c6a7d/source/200x200bb.jpg";
			var fileName = image.src.split(/(\\|\/)/g).pop();
			image.onload = function () {
			    var canvas = document.createElement('canvas');
			    canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
			    canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
			    canvas.getContext('2d').drawImage(this, 0, 0);
			    var blob;
			    // ... get as Data URI
			    if (image.src.indexOf(".jpg") > -1) {
			    blob = canvas.toDataURL("image/jpeg");
			    } else if (image.src.indexOf(".png") > -1) {
			    blob = canvas.toDataURL("image/png");
			    } else if (image.src.indexOf(".gif") > -1) {
			    blob = canvas.toDataURL("image/gif");
			    } else {
			    blob = canvas.toDataURL("image/png");
			    }
			    $("body").html("<b>點擊下載圖片.</b><br><a download='" + fileName + "' href='" + blob + "'><img src='" + blob + "'/></a>");
			};
		}
	</script>
</html>

方法三:(base64, ie不支持)

function downloadImgByBase64(url) {
	var img = new Image()
	img.onload = function() {
		var canvas = document.createElement('canvas')
		canvas.width = img.width
		canvas.height = img.height
		var ctx = canvas.getContext('2d')
		// 將img中的內容畫到畫布上
		ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
		// 將畫布內容轉換爲base64
		var base64 = canvas.toDataURL()
		// 創建a鏈接
		var a = document.createElement('a')
		a.href = base64
		a.download = ''
		// 觸發a鏈接點擊事件,瀏覽器開始下載文件
		a.click()
	}
	img.src = url
	// 必須設置,否則canvas中的內容無法轉換爲base64
	img.setAttribute('crossOrigin', 'Anonymous')
}

downloadImgByBase64('http://static.shuxuejia.com/img/201708020.gif');

方法二和方法三,效果都不太理想。因爲這兩種方法僅支持生成jpeg和png格式圖片。如果是gif圖,僅能顯示第一幀的內容。

不知道canvas轉化blob是不是就可以了???存疑一下。

後端實現:

(如果你怕兼容有問題,就讓後端寫一個下載的接口,參數是formData形式的。)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章