将 blob 转换为 base64 [英] Convert blob to base64

查看:452
本文介绍了将 blob 转换为 base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要对 Base64 字符串执行 Blob 的代码片段:

此注释部分有效,当由此生成的 URL 设置为 img src 时,它会显示图像:

var blob = items[i].getAsFile();//var URLObj = window.URL ||window.webkitURL;//var source = URLObj.createObjectURL(blob);//console.log("image source=" + source);var reader = new FileReader();reader.onload = 函数(事件){控制台日志(事件.目标.结果)};//数据地址!var source = reader.readAsBinaryString(blob);

问题出在下层代码,生成的源变量为空

更新:

是否有一种更简单的方法可以使用 JQuery 来从 Blob 文件创建 Base64 字符串,如上面的代码所示?

解决方案

var reader = new FileReader();reader.readAsDataURL(blob);reader.onloadend = function() {var base64data = reader.result;控制台日志(base64data);}

形成文档 readAsDataURL 编码为 base64

作为一个 awaitable 函数:

function blobToBase64(blob) {return new Promise((resolve, _) => {const reader = new FileReader();reader.onloadend = () =>解决(读者.结果);reader.readAsDataURL(blob);});}

<块引用>

注意:如果不先删除 Base64 编码数据之前的 Data-URL 声明,则无法将 blob 的结果直接解码为 Base64.要仅检索 Base64 编码的字符串,请先从结果中删除 data:/;base64.

This is a snippet for the code that I want to do Blob to Base64 string:

This commented part works and that when the URL generated by this is set to img src it displays the image:

var blob = items[i].getAsFile();
//var URLObj = window.URL || window.webkitURL;
//var source = URLObj.createObjectURL(blob);
//console.log("image source=" + source);

var reader = new FileReader();
reader.onload = function(event){
console.log(event.target.result)
}; // data url!
var source = reader.readAsBinaryString(blob);

The problem is with the the lower code, the source variable generated is null

Update:

Is there an easier way to do this with JQuery to be able to create Base64 String from Blob file as in the code above?

解决方案

var reader = new FileReader();
reader.readAsDataURL(blob); 
reader.onloadend = function() {
  var base64data = reader.result;                
  console.log(base64data);
}

Form the docs readAsDataURL encodes to base64

As an awaitable function:

function blobToBase64(blob) {
  return new Promise((resolve, _) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsDataURL(blob);
  });
}

Note: The blob's result cannot be directly decoded as Base64 without first removing the Data-URL declaration preceding the Base64-encoded data. To retrieve only the Base64 encoded string, first remove data:/;base64, from the result.

这篇关于将 blob 转换为 base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆