In order to realize the attachment download function in web pages, the download attribute of a tag is usually used, but for cross-domain image resources, the browser will directly open the image instead of downloading it.
<a download href="https://images.pexels.com/photos/15494499/pexels-photo-15494499.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1">图片下载</a>
plan 1
To process the image address page with the same source, you can configure the proxy in nginx to forward to the specified image address
location /image/ {
proxy_pass https://images.pexels.com/
}
Scenario 2
Use ajax in JavaScript to get the image content, then dynamically create the file address, and complete the download by simulating the click event of the a tag
<a href="#" onclick="download()" title="点击下载">图片下载</a>
<script>
function download() {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
let link = document.createElement("a");
let url = window.URL.createObjectURL(xhr.response);
link.href = url;
link.download = '1';
link.click();
window.URL.revokeObjectURL(url);
}
}
// 需要指定响应类型为 blob
xhr.responseType = "blob";
xhr.open("get", "https://images.pexels.com/photos/15494499/pexels-photo-15494499.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1");
xhr.send();
}
</script>