download
属性仅适用于同源网址:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
如果您确实不想告诉用户“左键单击,下载为等”,您可以尝试以下代码行周围的操作。但是,在将其实施到您的网站之前,我会研究 CORS,以确认它对于您的用例来说是安全的。
<script>
function saveFile(url) {
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
a.download = filename; // Set the file name.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
delete a;
};
xhr.open('GET', url);
xhr.send();
}
</script>
<a onclick="saveFile('https://images.unsplash.com/photo-1556911164-1297abe8527c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80')">Download</a>
请尝试这个。
`<a id="dataFileLink" href="https://images.unsplash.com/photo-1556911164-1297abe8527c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80" download style="">
<img src="https://images.unsplash.com/photo-1556911164-1297abe8527c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80" alt="Download Image">
</a>`