如何使用 JavaScript 将 base64 图像保存到用户磁盘? [英] How to save a base64 image to user's disk using JavaScript?

查看:27
本文介绍了如何使用 JavaScript 将 base64 图像保存到用户磁盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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.

如何实现我想要的?

推荐答案

HTML5 download 属性

为了允许用户下载图片或其他文件,您可以使用 HTML5 download 属性.

静态文件下载

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

动态文件下载

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

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

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

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

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

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

Otherwise if image file is downloaded as Blob you can use FileReader to convert it to 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 中的 DOM,以便被点击事件识别(链接).

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

不支持 IE:Caniuse 链接

这篇关于如何使用 JavaScript 将 base64 图像保存到用户磁盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆