How to Save a Base64 Image to User'S Disk Using JavaScript

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

HTML5 download attribute

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

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

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

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 is not supported: Caniuse link

How can I save a base64-encoded image to disk?

I think you are converting the data a bit more than you need to. Once you create the buffer with the proper encoding, you just need to write the buffer to the file.

var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, "");

require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
console.log(err);
});

new Buffer(..., 'base64') will convert the input string to a Buffer, which is just an array of bytes, by interpreting the input as a base64 encoded string. Then you can just write that byte array to the file.

Update

As mentioned in the comments, req.rawBody is no longer a thing. If you are using express/connect then you should use the bodyParser() middleware and use req.body, and if you are doing this using standard Node then you need to aggregate the incoming data event Buffer objects and do this image data parsing in the end callback.

How to store base64 as an image in file system in Javascript

You can simply open the base64 in a new tab using javascript:

window.location="data:image/jpeg;base64,ehfnshxfbsnxj";

To let the browser download it automatically use this snippet found on SO:

var link = document.createElement('a');  
link.href = 'data:image/jpeg;base64,sduebdueb'; link.download = 'coolimage.jpg';
document.body.appendChild(link);
link.click();


Related Topics



Leave a reply



Submit