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

时间:2013-07-08 13:19:09

标签: javascript jquery html

我需要浏览器下载图像文件,就像点击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工作表(浏览器做什么),它应该如何工作?

14 个答案:

答案 0 :(得分:142)

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

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

然后,合规浏览器将提示下载具有相同文件名的图像(在此示例中为image.png)。

如果为此属性指定了值,那么它将成为新文件名:

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

更新:截至2018年春季,对于跨源href已不再可能。因此,如果您想在imgur.com以外的域上创建<a href="https://i.imgur.com/IskAzqA.jpg" download>,则无法按预期工作。 Chrome deprecations and removals announcement

答案 1 :(得分:78)

我设法通过添加指向文档的链接在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);

答案 2 :(得分:20)

  

Leeroy&amp; Richard Parnaby-King:

     

更新:自2018年春季开始,这不再是交叉起源   的HREF。因此,如果您想在imgur.com以外的域上创建它   不会按预期工作。 Chrome deprecations and removals announcement

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

答案 3 :(得分:10)

更新2018年春季

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

虽然仍然支持此功能,但截至2018年2月,Chrome已禁用此功能以进行跨源下载,这意味着仅当文件位于同一域名时才会生效。

我找到了在Chrome新更新禁用跨域下载后下载跨域图像的解决方法。您可以将其修改为适合您需求的功能。如果需要的话,你可以通过更多的研究获得图像mime-type(jpeg,png,gif等)。也许有一种方法可以与视频做类似的事情。希望这有助于某人!

  

Leeroy&amp; Richard Parnaby-King:

     
    

更新:自2018年春季开始,这不再是交叉起源     的HREF。因此,如果您想在其他域上创建     比imgur.com它不会按预期工作。 Chrome deprecations and removals announcement

  

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>

答案 4 :(得分:5)

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

&#13;
&#13;
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/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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ttsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/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>
&#13;
{{1}}
&#13;
&#13;
&#13;

答案 5 :(得分:3)

2020年,我使用Blob制作图像的本地副本,该浏览器将下载为文件。您可以在此site上对其进行测试。

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

答案 6 :(得分:1)

试试这个:

server <- function(input, output) {

  #This function is repsonsible for loading in the selected file
  filedata <- reactive({
    infile <- input$datafile
    if (is.null(infile)) {
      # User has not uploaded a file yet
      return(NULL)
    }
    read.dbf(infile$datapath)
  })



  output$mytable <- renderDataTable({
    filedata()
  })

  output$plot_kpm <- renderPlot({
    get_calculate(filedata(), tolerance = input$tol)$kpm_chart
  })

 output$table_kpm <- renderTable({
    get_calculate(filedata(), tolerance = input$tol)$data_kpm[, c("Time", "Percent", "Patients")]
  })


 output$download_mainboard_adherence_table <- downloadHandler(
                                               filename = paste("adherence_table", '.csv', sep=''),
                                               content = function(file) {
                                                 write.csv(get_calculate(filedata(), tolerance = input$tol)$data_kpm[, c("Time", "Percent", "Patients")], file)
   }
 )

}

答案 7 :(得分:1)

您可以使用 anchor标记直接下载此文件,而无需太多代码。
复制该代码段并粘贴到文本编辑器中,然后尝试...!

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

答案 8 :(得分:1)

使用Promise和async / await的更现代的方法:

toDataURL(url) {
    return fetch(url).then((response) => {
            return response.blob();
        }).then(blob => {
            return URL.createObjectURL(blob);
        });
}

然后

async 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

答案 9 :(得分:0)

使用.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>

答案 10 :(得分:0)

创建一个接收图像 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>

答案 11 :(得分:-1)

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

答案 12 :(得分:-5)

我找到了

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

对我不起作用。我不确定为什么。

我发现您可以在链接末尾添加?download=true参数以强制下载。我想我注意到Google云端硬盘正在使用这种技术。

在您的链接中,请在href的末尾添加?download=true

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

在您的链接中,请在href的末尾添加?download=true&filename=My_Image_File.jpeg

答案 13 :(得分:-15)

您不需要编写js来执行此操作,只需使用:

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

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

如果由于某种原因无效则添加下载属性。 使用此属性,您可以为可下载文件设置名称:

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