强制浏览器在单击时下载图像文件

我需要浏览器下载的图像文件,就像它在一个 Excel 工作表上点击。

有没有办法只使用客户端编程来实现这一点?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.10.2.js">
$(document).ready(function () {
$("*").click(function () {
$("p").hide();
});
});
</script>
</head>


<script type="text/javascript">
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.innerHTML == "Image") {
//someFunction(element.href);
var name = element.nameProp;
var address = element.href;
saveImageAs1(element.nameProp, element.href);
return false; // Prevent default action and stop event propagation
}
else
return true;
};


function saveImageAs1(name, adress) {
if (confirm('you wanna save this image?')) {
window.win = open(adress);
//response.redirect("~/testpage.html");
setTimeout('win.document.execCommand("SaveAs")', 100);
setTimeout('win.close()', 500);
}
}
</script>


<body>
<form id="form1" runat="server">
<div>
<p>
<a href="http://localhost:55298/SaveImage/demo/Sample2.xlsx" target="_blank">Excel</a><br />
<a href="http://localhost:55298/SaveImage/demo/abc.jpg" id="abc">Image</a>
</p>
</div>
</form>
</body>
</html>

在下载 Excel 表格的情况下它应该如何工作(浏览器做什么) ?

410714 次浏览

使用 HTML5,您可以将属性“ download”添加到您的链接中。

<a href="/path/to/image.png" download>

符合要求的浏览器将提示下载具有相同文件名的图像(在本例中为 image.png)。

如果您为这个属性指定一个值,那么它将成为新的文件名:

<a href="/path/to/image.png" download="AwesomeImage.png">

更新: 从2018年春天开始,交叉来源的 hrefs已经不可能了。因此,如果您想在 imgur.com 以外的域上创建 <a href="https://i.imgur.com/IskAzqA.jpg" download>,它将无法按预期工作。Chrome 弃用和移除声明

您不需要编写 js 来完成这项工作,只需使用:

<a href="path_to/image.jpg" alt="something">Download image</a>

浏览器会自动下载图像。

如果由于某种原因它不工作,添加下载属性。 使用这个属性,您可以设置可下载文件的名称:

<a href="path_to/image.jpg" download="myImage">Download image</a>

通过在 to 文档中添加一个链接,我成功地在 Chrome 和 Firefox 中实现了这个功能。

var link = document.createElement('a');
link.href = 'images.jpg';
link.download = 'Download.jpg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
<html>
<head>
<script type="text/javascript">
function prepHref(linkElement) {
var myDiv = document.getElementById('Div_contain_image');
var myImage = myDiv.children[0];
linkElement.href = myImage.src;
}
</script>
</head>
<body>
<div id="Div_contain_image"><img src="YourImage.jpg" alt='MyImage'></div>
<a href="#" onclick="prepHref(this)" download>Click here to download image</a>
</body>
</html>

我发现的

<a href="link/to/My_Image_File.jpeg" download>Download Image File</a>

不适合我。我不知道为什么。

我发现可以在链接末尾包含一个 ?download=true参数来强制下载。我想我注意到了 Google Drive 正在使用这种技术。

在你的链接,包括 ?download=true在你的 href 结束。

您还可以使用此技术同时设置文件名。

在你的链接,包括 ?download=true&filename=My_Image_File.jpeg在你的 href 结束。

var pom = document.createElement('a');
pom.setAttribute('href', 'data:application/octet-stream,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);

这是解决你问题的通用方法。但是有一个非常重要的部分,即文件扩展名应该与您的编码相匹配。当然,downlowadImage 函数的 content 参数应该是图像的 base64编码字符串。

const clearUrl = url => url.replace(/^data:image\/\w+;base64,/, '');


const downloadImage = (name, content, type) => {
var link = document.createElement('a');
link.style = 'position: fixed; left -10000px;';
link.href = `data:application/octet-stream;base64,${encodeURIComponent(content)}`;
link.download = /\.\w+/.test(name) ? name : `${name}.${type}`;


document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}


['png', 'jpg', 'gif'].forEach(type => {
var download = document.querySelector(`#${type}`);
download.addEventListener('click', function() {
var img = document.querySelector('#img');


downloadImage('myImage', clearUrl(img.src), type);
});
});
a gif image: <image id="img" src="data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6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EAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==" />




<button id="png">Download PNG</button>
<button id="jpg">Download JPG</button>
<button id="gif">Download GIF</button>

试试这个:

<a class="button" href="http://www.glamquotes.com/wp-content/uploads/2011/11/smile.jpg" download="smile.jpg">Download image</a>

2018年春季更新

<a href="/path/to/image.jpg" download="FileName.jpg">

虽然这仍然是支持的,截至2018年2月,铬禁用这一功能的跨源下载意味着,这将只有工作,如果文件位于相同的域名。

我想出了一个解决方案,下载跨域图片后,Chrome 的新更新,禁止跨域下载。您可以将其修改为适合您需要的函数。如果需要的话,您可以通过更多的研究获得图像 mime 类型(jpeg、 png、 gif 等)。也许有一种方法可以在视频中做类似的事情。希望这对谁有帮助!

Leeroy & Richard Parnaby-King:

更新: 截至2018年春季,这不再是可能的跨原产地 因此,如果你想创建一个域名其他 比 imgur.com 更糟糕的是,它不会像预期的那样工作 清除行动公告

var image = new Image();
image.crossOrigin = "anonymous";
image.src = "https://is3-ssl.mzstatic.com/image/thumb/Music62/v4/4b/f6/a2/4bf6a267-5a59-be4f-6947-d803849c6a7d/source/200x200bb.jpg";
// get file name - you might need to modify this if your image url doesn't contain a file extension otherwise you can set the file name manually
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>Click image to download.</b><br><a download='" + fileName + "' href='" + blob + "'><img src='" + blob + "'/></a>");
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Leeroy & Richard Parnaby-King:

更新: 截至2018年春季,这不再是可能的跨原产地 所以如果你想在 imgur.com 以外的域名上创建它 不会像预期的那样工作。“一个 href = “ https://developers.google.com/web/update/2018/02/Chrome-65-depecations # block _ cross-source _ wzxhzdk5a _ download”rel = “ norefrer”> Chrome 的弃用和删除 公告

function forceDownload(url, fileName){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}

您可以使用 锚标签直接下载这个文件,而不需要很多代码。< br > 复制代码片段并粘贴到文本编辑器中,然后尝试... !

<html>
<head>
</head>
<body>
<div>
<img src="https://upload.wikimedia.org/wikipedia/commons/1/1f/SMirC-thumbsup.svg" width="200" height="200">
<a href="#" download="https://upload.wikimedia.org/wikipedia/commons/1/1f/SMirC-thumbsup.svg"> Download Image </a>
</div>
</body>
</html>

一种更加现代的方法,使用的是  诺和异步/等待:

async function toDataURL(url) {
const blob = await fetch(url).then(res => res.blob());
return URL.createObjectURL(blob);
}

那么

async function download() {
const a = document.createElement("a");
a.href = await toDataURL("https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png");
a.download = "myImage.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}

在这里找到文档: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

使用. click ()函数和标记怎么样?

(压缩版)

<a id="downloadtag" href="examplefolder/testfile.txt" hidden download></a>


<button onclick="document.getElementById('downloadtag').click()">Download</button>

现在你可以用 js 来触发它,它也不会像其他例子一样打开图片和文本文件!

(js- 函数版本)

function download(){
document.getElementById('downloadtag').click();
}
<!-- HTML -->
<button onclick="download()">Download</button>
<a id="downloadtag" href="coolimages/awsome.png" hidden download></a>

在2020年,我使用 团团制作本地的图像副本,浏览器将作为一个文件下载。你可以在这个 工地上测试它。

enter image description here

(function(global) {
const next = () => document.querySelector('.search-pagination__button-text').click();
const uuid = () => Math.random().toString(36).substring(7);
const toBlob = (src) => new Promise((res) => {
const img = document.createElement('img');
const c = document.createElement("canvas");
const ctx = c.getContext("2d");
img.onload = ({target}) => {
c.width = target.naturalWidth;
c.height = target.naturalHeight;
ctx.drawImage(target, 0, 0);
c.toBlob((b) => res(b), "image/jpeg", 0.75);
};
img.crossOrigin = "";
img.src = src;
});
const save = (blob, name = 'image.png') => {
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.target = '_blank';
a.download = name;
a.click();
};
global.download = () => document.querySelectorAll('.search-content__gallery-results figure > img[src]').forEach(async ({src}) => save(await toBlob(src), `${uuid()}.png`));
global.next = () => next();
})(window);

创建一个接收图像 URL 和文件名的函数,并使用按钮调用该函数。

function downloadImage(url, name){
fetch(url)
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// the filename you want
a.download = name;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})
.catch(() => alert('An error sorry'));
}
<button onclick="downloadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Stack_Overflow_logo.svg/1280px-Stack_Overflow_logo.svg.png', 'LogoStackOverflow.png')" >DOWNLOAD</button>

Codepen.io Force image download with JavaScript

vladi.codes

你可以的

const urls = ['image.png', 'image1.png'];
urls.forEach((url) => {
window.open(url, "_blank");
});
    // Pass desired URL as a param
function saveAs(uri) {
fetch(uri)
.then(res => res.blob()) // Gets the response and returns it as a blob
.then(blob => {
// Here, I use it to make an image appear on the page
let objectURL = URL.createObjectURL(blob);
let myImage = new Image();
myImage.href = blob;
myImage.download = generateFileName();
//Firefox requires the link to be in the body
document.body.appendChild(myImage);
//simulate click
myImage.click();
//remove the link when done
document.body.removeChild(myImage);
});
}


// Generate filenames for the image which is to be downloaded
function generateFileName() {
return `img${Math.floor(Math.random() * 90000) + 10000}`;
}
<!DOCTYPE html>
<html>
<body>
<button onclick="forceDownload('http://localhost:4000/1-2-free-png-image.png','test.png')">Download</button>




<script>
function forceDownload(url, fileName){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}
</script>
</body>
</html>