如何使用 JavaScript 将 base64 图像保存到用户的磁盘?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7951326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:10:50  来源:igfitidea点击:

How to save a base64 image to user's disk using JavaScript?

javascripthtmlimagebase64save

提问by vengatesh

I have converted the source content from the <img>html tag to a base64String using JavaScript. The image was displayed clearly. Now I want to save that image to user's disk using javascript.

我已<img>使用 JavaScript将源内容从html 标记转换为 base64String。图像显示清晰。现在我想使用 javascript 将该图像保存到用户的磁盘。

<html>
    <head>
    <script>
        function saveImageAs () {
            var imgOrURL;
            embedImage.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA" +
                             "AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO" +
                             "9TXL0Y4OHwAAAABJRU5ErkJggg==";
            imgOrURL = embedImage;
            if (typeof imgOrURL == 'object')
                imgOrURL = embedImage.src;
            window.win = open(imgOrURL);
            setTimeout('win.document.execCommand("SaveAs")', 0);
        }
    </script>
    </head>
    <body>
        <a href="#" ONCLICK="saveImageAs(); return false" >save image</a>

        <img id="embedImage" alt="Red dot">
    </body>
</html>

This code worked well when I set the image path as source for <img>html tag. However, when I pass the source as base64String does not work.

当我将图像路径设置为<img>html 标记的源时,此代码运行良好。但是,当我将源作为 base64String 传递时不起作用。

How to achieve what I want?

如何实现我想要的?

回答by Andrii Verbytskyi

HTML5 downloadattribute

HTML5download属性

Just to allow user to download the image or other file you may use the HTML5 downloadattribute.

只是为了允许用户下载图像或其他文件,您可以使用 HTML5download属性。

Static file download

静态文件下载

<a href="/images/image-name.jpg" download>
<!-- OR -->
<a href="/images/image-name.jpg" download="new-image-name.jpg"> 

Dynamic file download

动态文件下载

In cases requesting image dynamically it is possible to emulate such download.

在动态请求图像的情况下,可以模拟这样的下载。

If your image is already loaded and you have the base64source then:

如果您的图像已经加载并且您base64有源,则:

function saveBase64AsFile(base64, fileName) {
    var link = document.createElement("a");

    document.body.appendChild(link); // for Firefox

    link.setAttribute("href", base64);
    link.setAttribute("download", fileName);
    link.click();
}

Otherwise if image file is downloaded as Blobyou can use FileReaderto convert it to Base64:

否则,如果下载了图像文件,Blob您可以FileReader将其转换为 Base64:

function saveBlobAsFile(blob, fileName) {
    var reader = new FileReader();

    reader.onloadend = function () {    
        var base64 = reader.result ;
        var link = document.createElement("a");

        document.body.appendChild(link); // for Firefox

        link.setAttribute("href", base64);
        link.setAttribute("download", fileName);
        link.click();
    };

    reader.readAsDataURL(blob);
}

Firefox

火狐

The anchor tag you are creating also needs to be added to the DOM in Firefox, in order to be recognized for click events (Link).

您正在创建的锚标记还需要添加到 Firefox 中的 DOM,以便识别点击事件 ( Link)。

IE is not supported: Caniuse link

不支持 IE: Caniuse 链接

回答by John Doe

In JavaScript you cannot have the direct access to the filesystem. However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replacemethod with your Base64String and replace "image/png"with "image/octet-stream":

在 JavaScript 中,您无法直接访问文件系统。但是,您可以让浏览器弹出一个对话窗口,允许用户选择保存位置。为此,请将该replace方法与您的 Base64String 一起使用并替换"image/png""image/octet-stream"

"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");


Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:

此外,符合 W3C 的浏览器提供了 2 种处理 base64 编码和二进制数据的方法:

Probably, you will find them useful in a way...

也许,你会发现它们在某种程度上很有用......



Here is a refactored version of what I understand you need:

这是我理解您需要的重构版本:

window.addEventListener('DOMContentLoaded', () => {
  const img = document.getElementById('embedImage');
  img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +
    'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +
    '9TXL0Y4OHwAAAABJRU5ErkJggg==';

  img.addEventListener('load', () => button.removeAttribute('disabled'));
  
  const button = document.getElementById('saveImage');
  button.addEventListener('click', () => {
    window.location.href = img.src.replace('image/png', 'image/octet-stream');
  });
});
<!DOCTYPE html>
<html>

<body>
  <img id="embedImage" alt="Red dot" />
  <button id="saveImage" disabled="disabled">save image</button>
</body>

</html>