谷歌浏览器通过a标签下载图片的问题

1,276 阅读1分钟

在公司开发2年,谷歌浏览器通过a标签下载图片都没有发现有问题,然而这几天开发时发现,谷歌浏览器通过a标签下载图片会直接打开图片地址链接

原来是后端人员设置了下载图片链接

针对该问题解决方法及分析如下:

方法四:Blob方法

方法有效,但是必须设置download值,并且不能为空。

export const downloadImage = (imgUrl, download) => {
    function toDataURL(url) {
        return fetch(url).then((response) => {
                return response.blob();
            }).then(blob => {
                return URL.createObjectURL(blob);
            });
    }
    (async function() {
            const a = document.createElement("a");
            imgUrl = imgUrl+'?'+Math.random()
            a.href = await toDataURL(imgUrl);
            a.setAttribute('download', download ? download:'pic.png')
            a.click();
    })()
}

方法三:通过XMLHttpRequest()请求图片链接,然后获取返回的Blob

方法有效,但是必须设置download值,并且不能为空。

var x = new XMLHttpRequest();
x.open("GET", url, 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 = 'qrcode.png'
  a.click()
}
x.send();

方法二: 会直接打开图片地址,将原先地址覆盖

var $a = document.createElement('a');
$a.setAttribute("href", url);
$a.setAttribute("download", "qrcode");
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
$a.dispatchEvent(evObj);

方法一: 会直接打开图片地址,将原先地址覆盖

let a = document.createElement('a');
a.setAttribute('download', 'qrcode.png')
a.href = url + '?' + new Date().getTime()
a.click()

参考链接: HTML+JS实现浏览器下载图片