强制浏览器下载图像文件的点击。

时间:2022-04-01 07:32:02

I need the browser to download the image files just as it does while clicking on an Excel sheet.

我需要浏览器下载图像文件,就像在点击Excel表格时一样。

Is there a way to do this using client-side programming only?

是否有办法只使用客户端编程?

<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>

How should it work in case of downloading an Excel sheet (what browsers do)?

在下载Excel表格(浏览器会做什么)时,它应该如何工作?

10 个解决方案

#1


119  

Using HTML5 you can add the attribute 'download' to your links.

使用HTML5,你可以将“下载”属性添加到链接中。

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

< a href = " /道路/ /形象。png "下载>

Compliant browsers will then prompt to download the image with the same file name (in this example image.png).

兼容的浏览器将提示下载具有相同文件名的图像(在本例中是image.png)。

If you specify a value for this attribute, then that will become the new filename:

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

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

< a href = " /道路/ /形象。png AwesomeImage.png“下载= >

UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create <a href="https://i.imgur.com/IskAzqA.jpg" download> on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement

更新:截止到2018年春季,这已不再适用于交叉起源的hrefs。因此,如果你想在imgur.com之外的域名上下载>,那么它将无法正常工作。Chrome不赞成和删除声明。

#2


61  

I managed to get this working in Chrome and Firefox too by appending a link to the to document.

我成功地在Chrome和Firefox中完成了这个工作,并添加了一个到文档的链接。

var link = document.createElement('a');
link.href = 'images.jpg';
link.download = 'Download.jpg';
document.body.appendChild(link);
link.click();

#3


8  

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);     

#4


5  

This is a general solution to your problem. But there is one very important part that the file extension should match your encoding. And of course, that content parameter of downlowadImage function should be base64 encoded string of your image.

这是你问题的通解。但是有一个非常重要的部分,文件扩展应该与您的编码相匹配。当然,downlowadImage函数的内容参数应该是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/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8J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/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>

#5


2  

Leeroy & Richard Parnaby-King:

Leeroy &理查德·Parnaby-King:

UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement

更新:截止到2018年春季,这已不再适用于交叉起源的hrefs。因此,如果你想在imgur.com之外的域名上创建,它将不会像预期的那样工作。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();
}

#6


1  

Try this:

试试这个:

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

#7


0  

<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>

#8


0  

Update Spring 2018

更新2018年春季

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

While this is still supported, as of February 2018 chrome disabled this feature for cross-origin downloading meaning this will only work if the file is located on the same domain name.

虽然这仍然得到支持,但是到2018年2月,chrome已经禁用了这一功能,这意味着如果文件位于相同的域名下,这将只会起作用。

I figured out a workaround for downloading cross domain images after Chrome's new update which disabled cross domain downloading. You could modify this into a function to suit your needs. You might be able to get the image mime-type (jpeg,png,gif,etc) with some more research if you needed to. There may be a way to do something similar to this with videos as well. Hope this helps someone!

我想出了一个解决方案,在Chrome的新更新后,可以下载跨域图像,这是禁止跨域下载的。您可以将其修改为适合您需要的函数。如果你需要的话,你可能会得到一些更多的研究的图像mime-type (jpeg,png,gif等)。在视频中也可能有类似的方法。希望这可以帮助别人!

Leeroy & Richard Parnaby-King:

Leeroy &理查德·Parnaby-King:

UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement

更新:截止到2018年春季,这已不再适用于交叉起源的hrefs。因此,如果你想在imgur.com之外的域名上创建,它将不会像预期的那样工作。Chrome不赞成和删除声明。

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";
// 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>

#9


-3  

I found that

我发现

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

下载图像文件 。

did not work for me. I'm not sure why.

对我不起作用。我不知道为什么。

I have found that you can include a ?download=true parameter at the end of your link to force a download. I think I noticed this technique being used by Google Drive.

我发现您可以在链接的最后添加一个下载=true参数来强制下载。我想我注意到谷歌驱动器使用了这种技术。

In your link, include ?download=true at the end of your href.

在你的链接中,包括?下载=true在你的href结尾。

You can also use this technique to set the filename at the same time.

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

In your link, include ?download=true&filename=My_Image_File.jpeg at the end of your href.

在您的链接中,包括下载=true&filename=My_Image_File.jpeg在您的href结尾。

#10


-14  

You don't need to write js to do that, simply use:

你不需要写js来做那件事,简单地说:

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

And the browser itself will automatically download the image.

而浏览器本身会自动下载图像。

If for some reason it doesn't work add the download attribute. With this attribute you can set a name for the downloadable file:

如果由于某种原因,它不能添加下载属性。有了这个属性,您可以为可下载文件设置名称:

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

#1


119  

Using HTML5 you can add the attribute 'download' to your links.

使用HTML5,你可以将“下载”属性添加到链接中。

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

< a href = " /道路/ /形象。png "下载>

Compliant browsers will then prompt to download the image with the same file name (in this example image.png).

兼容的浏览器将提示下载具有相同文件名的图像(在本例中是image.png)。

If you specify a value for this attribute, then that will become the new filename:

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

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

< a href = " /道路/ /形象。png AwesomeImage.png“下载= >

UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create <a href="https://i.imgur.com/IskAzqA.jpg" download> on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement

更新:截止到2018年春季,这已不再适用于交叉起源的hrefs。因此,如果你想在imgur.com之外的域名上下载>,那么它将无法正常工作。Chrome不赞成和删除声明。

#2


61  

I managed to get this working in Chrome and Firefox too by appending a link to the to document.

我成功地在Chrome和Firefox中完成了这个工作,并添加了一个到文档的链接。

var link = document.createElement('a');
link.href = 'images.jpg';
link.download = 'Download.jpg';
document.body.appendChild(link);
link.click();

#3


8  

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);     

#4


5  

This is a general solution to your problem. But there is one very important part that the file extension should match your encoding. And of course, that content parameter of downlowadImage function should be base64 encoded string of your image.

这是你问题的通解。但是有一个非常重要的部分,文件扩展应该与您的编码相匹配。当然,downlowadImage函数的内容参数应该是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/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5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W6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==" />


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

#5


2  

Leeroy & Richard Parnaby-King:

Leeroy &理查德·Parnaby-King:

UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement

更新:截止到2018年春季,这已不再适用于交叉起源的hrefs。因此,如果你想在imgur.com之外的域名上创建,它将不会像预期的那样工作。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();
}

#6


1  

Try this:

试试这个:

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

#7


0  

<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>

#8


0  

Update Spring 2018

更新2018年春季

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

While this is still supported, as of February 2018 chrome disabled this feature for cross-origin downloading meaning this will only work if the file is located on the same domain name.

虽然这仍然得到支持,但是到2018年2月,chrome已经禁用了这一功能,这意味着如果文件位于相同的域名下,这将只会起作用。

I figured out a workaround for downloading cross domain images after Chrome's new update which disabled cross domain downloading. You could modify this into a function to suit your needs. You might be able to get the image mime-type (jpeg,png,gif,etc) with some more research if you needed to. There may be a way to do something similar to this with videos as well. Hope this helps someone!

我想出了一个解决方案,在Chrome的新更新后,可以下载跨域图像,这是禁止跨域下载的。您可以将其修改为适合您需要的函数。如果你需要的话,你可能会得到一些更多的研究的图像mime-type (jpeg,png,gif等)。在视频中也可能有类似的方法。希望这可以帮助别人!

Leeroy & Richard Parnaby-King:

Leeroy &理查德·Parnaby-King:

UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement

更新:截止到2018年春季,这已不再适用于交叉起源的hrefs。因此,如果你想在imgur.com之外的域名上创建,它将不会像预期的那样工作。Chrome不赞成和删除声明。

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";
// 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>

#9


-3  

I found that

我发现

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

下载图像文件 。

did not work for me. I'm not sure why.

对我不起作用。我不知道为什么。

I have found that you can include a ?download=true parameter at the end of your link to force a download. I think I noticed this technique being used by Google Drive.

我发现您可以在链接的最后添加一个下载=true参数来强制下载。我想我注意到谷歌驱动器使用了这种技术。

In your link, include ?download=true at the end of your href.

在你的链接中,包括?下载=true在你的href结尾。

You can also use this technique to set the filename at the same time.

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

In your link, include ?download=true&filename=My_Image_File.jpeg at the end of your href.

在您的链接中,包括下载=true&filename=My_Image_File.jpeg在您的href结尾。

#10


-14  

You don't need to write js to do that, simply use:

你不需要写js来做那件事,简单地说:

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

And the browser itself will automatically download the image.

而浏览器本身会自动下载图像。

If for some reason it doesn't work add the download attribute. With this attribute you can set a name for the downloadable file:

如果由于某种原因,它不能添加下载属性。有了这个属性,您可以为可下载文件设置名称:

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