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形式的。)

    原文作者:街边吃垃圾
    原文地址: https://blog.csdn.net/zhangjing0320/article/details/94724956
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞