简体   繁体   English

解码base64图像并上传

[英]Decode base64 image and upload

I have a webapp that is saving images locally until they are ready to be sent to the server. 我有一个webapp,它将图像保存在本地,直到准备好将其发送到服务器为止。 When I save the images locally, I base64 encode them. 当我将图像保存在本地时,我对它们进行了base64编码。 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, 我试过使用FileReader像这样将其转换回原位,

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. 但是onloadend事件不会触发,也没有错误。 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. 不熟悉FileReader,但我相信readAsBinaryString期望使用Blob或File对象。 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? 查阅本文,了解编码/解码Base64的方法: 如何使用Javascript编码为Base64?

Looks like you can use btoa() and atob() for web kit browsers. 看起来您可以将btoa()和atob()用于Web工具包浏览器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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