在angularjs中转换base64数据图像文件

在将base64文件转换为angularjs中的图像时获取损坏的文件任何人都可以建议我如何将base64文件转换为angularjs中的图像

我使用此方法将base64文件转换为图像

var imageBase64 =“image base64 data”; var blob = new Blob([imageBase64],{type:’image / png’});

从这个blob中,您可以生成文件对象。

var file = new File([blob],’imageFileName.png’);

首先,将dataURL转换为Blob执行此操作

var blob = dataURItoBlob(imageBase64); function dataURItoBlob(dataURI) { // convert base64/URLEncoded data component to raw binary data held in a string var byteString; if (dataURI.split(',')[0].indexOf('base64') >= 0) byteString = atob(dataURI.split(',')[1]); else byteString = unescape(dataURI.split(',')[1]); // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // write the bytes of the string to a typed array var ia = new Uint8Array(byteString.length); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new Blob([ia], {type:mimeString}); } 

然后

 var file = new File([blob], 'fileName.jpeg', {type: "'image/jpeg"}); 

您的代码看起来没问题,除了一点:

您提供给Blob对象的数据不是blob数据,它是一个文本,它是base64编码的。 您应该在插入之前解码数据。

一旦我不知道你想要哪个API,我将使用一个名为decodeBase64的伪函数,我们将理解它是Base64编码的反函数(在web中有很多这个函数的实现)。

您的代码应如下所示:

 // base64 already encoded data var imageBase64 = "image base64 data"; //this is the point you should use decodedImage = decodeBase64(imageBase64) //now, use the decodedData instead of the base64 one var blob = new Blob([decodedImage], {type: 'image/png'}); ///now it should work properly var file = new File([blob], 'imageFileName.png'); 

无论如何,一旦你还没有使用AngularJS,我看不出需要。