Sag*_*tel 5 javascript jquery angularjs
在将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');
byt*_*0de 13
首先,将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});
}
Run Code Online (Sandbox Code Playgroud)
然后
var file = new File([blob], "fileName.jpeg", {
type: "'image/jpeg'"
});
Run Code Online (Sandbox Code Playgroud)
除了一点之外,您的代码看起来不错:
您提供给 Blob 对象的数据不是 blob 数据,而是经过 base64 编码的文本数据。您应该在插入之前解码数据。
一旦我不知道您想要哪个API,我将使用一个名为decodeBase64的伪函数,我们将理解它执行Base64编码的逆操作(在网络中有许多此函数的实现)。
您的代码应如下所示:
// 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');
Run Code Online (Sandbox Code Playgroud)
不管怎样,一旦你还没有使用 AngularJS,我就看不出有必要使用 AngularJS。
| 归档时间: |
|
| 查看次数: |
8982 次 |
| 最近记录: |