admin管理员组

文章数量:1312889

I'm trying to use FileSaver.js to download PNG files that are being served from my express app. The files are being sent as base64 encoded strings, but when I try to use FileSaver.js to save them they bee corrupted.

This is the way I'm trying to save them:

var blob = new Blob([base64encodedString], {type: "data:image/png;base64"});
saveAs(blob, "image.png");

I've also used this method of saving the images, but it doesn't work if the base64encodedString bees too large:

var download = document.createElement('a');
download.href = 'data:image/png;base64,' + base64encodedString;  
download.download = 'reddot.png';
download.click();

What am I doing wrong with the FileSaver.js?

I'm trying to use FileSaver.js to download PNG files that are being served from my express app. The files are being sent as base64 encoded strings, but when I try to use FileSaver.js to save them they bee corrupted.

This is the way I'm trying to save them:

var blob = new Blob([base64encodedString], {type: "data:image/png;base64"});
saveAs(blob, "image.png");

I've also used this method of saving the images, but it doesn't work if the base64encodedString bees too large:

var download = document.createElement('a');
download.href = 'data:image/png;base64,' + base64encodedString;  
download.download = 'reddot.png';
download.click();

What am I doing wrong with the FileSaver.js?

Share Improve this question asked Oct 20, 2015 at 17:23 martinmartin 1,9744 gold badges39 silver badges70 bronze badges 2
  • Check the base64 string and make sure it displays the image, you can use an online base64 converter for this if you need to. it might be corrupted before you send it to the File Saver so check that it's valid first. – Joshua Duxbury Commented Oct 20, 2015 at 17:31
  • @JoshLeeDucks I've been trying to convert it using an online tool, but haven't had any success, but when I use the second method for downloading the (smallest) images it works so it should work for the Blob method too. – martin Commented Oct 20, 2015 at 17:43
Add a ment  | 

1 Answer 1

Reset to default 4

I've found that you'll probably want to write it to a Canvas first.

Click Here

base_image = new Image();
base_image.src = Base64String

canvas into a blob

var canvas = document.getElementById('YourCanvas');
context = canvas.getContext('2d');
// Draw image within
context.drawImage(base_image, 0,0);

then you can use FileSaver.js to save it

and finally save it

x_canvas.toBlob(function(blob) {
saveAs(blob, "screenshot.png");
}, "image/png");

A nice fiddle was also created for this in that post Click Here For Fiddle

本文标签: javascriptSaving PNG files with FileSaverjsStack Overflow