简体   繁体   中英

Decode base64 image and upload

I have a webapp that is saving images locally until they are ready to be sent to the server. When I save the images locally, I base64 encode them. Now I want to do a multipart file upload with these images.

So I need to convert the image back into binary form. I've tried using the FileReader to convert it back like this,

var fr = new FileReader();
fr.onloadend = function(binaryImage){
    debugger;
    binaryImage;
};
var base64Str = item.base64Image.substr(item.base64Image.indexOf("base64") + 7);
//var base64Str = item.base64Image;
fr.readAsBinaryString(base64Str);

but the onloadend event is never fired and there are no errors. Once I get the image I wont have trouble uploading it. Any ideas?

Thanks!

Not to familiar with FileReader, but I believe readAsBinaryString is expecting a Blob or File object. Passing it a string causes errors on my end. Try this:

var fr = new FileReader();
fr.onloadend = function(binaryImage){
    debugger;
    binaryImage;
};
var blob = new Blob([item.base64Image.
                          substr(item.base64Image.indexOf("base64") + 7)]);
fr.readAsBinaryString(blob);

I don't think this will give you want though. Check out this article for ways to encode/decode Base64: How can you encode to Base64 using Javascript?

Looks like you can use btoa() and atob() for web kit browsers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM