Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

javascript - Browser/HTML Force download of image from src="data:image/jpeg;base64..."

I am generating a image on client side and I display it with HTML like this:

<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgM...."/>

I want to offer the possibility to download the generated Image.

How can I realize that the browser is opening a file save dialoge (or just download the image like chrome or firefox to the download folder would do) which allows the user to save the image without doing right click and save as on the image?

I would prefer a solution without server interaction. So I am aware that it would be possible if I first upload the Image and then start the download.

Thanks a lot!

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply replace image/jpeg with application/octet-stream. The client would not recognise the URL as an inline-able resource, and prompt a download dialog.

A simple JavaScript solution would be:

//var img = reference to image
var url = img.src.replace(/^data:image/[^;]+/, 'data:application/octet-stream');
window.open(url);
// Or perhaps: location.href = url;
// Or even setting the location of an <iframe> element, 

Another method is to use a blob: URI:

var img = document.images[0];
img.onclick = function() {
? ??// atob to base64_decode the data-URI
? ??var image_data = atob(img.src.split(',')[1]);
    // Use typed arrays to convert the binary data to a Blob
? ??var arraybuffer = new ArrayBuffer(image_data.length);
? ??var view = new Uint8Array(arraybuffer);
? ??for (var i=0; i<image_data.length; i++) {
? ? ? ??view[i] = image_data.charCodeAt(i) & 0xff;
? ??}
    try {
        // This is the recommended method:
        var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
    } catch (e) {
        // The BlobBuilder API has been deprecated in favour of Blob, but older
        // browsers don't know about the Blob constructor
        // IE10 also supports BlobBuilder, but since the `Blob` constructor
        //  also works, there's no need to add `MSBlobBuilder`.
        var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
? ??    bb.append(arraybuffer);
? ??    var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob
    }

    // Use the URL object to create a temporary URL
? ? var url = (window.webkitURL || window.URL).createObjectURL(blob);
? ??location.href = url; // <-- Download!
};

Relevant documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...