jQuery 将 blob 转换为 base64

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18650168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:08:34  来源:igfitidea点击:

Convert blob to base64

javascriptjquery

提问by quarks

This is a snippet for the code that I want to do Blobto Base64string:

这是我想BlobBase64字符串执行的代码片段:

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

此注释部分有效,当由此生成的 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 = 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?

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

回答by Arun Killu

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

Form the docsreadAsDataURLencodes to base64

文档readAsDataURL编码为 base64

回答by yeahdixon

this worked for me:

这对我有用:

var blobToBase64 = function(blob, callback) {
    var reader = new FileReader();
    reader.onload = function() {
        var dataUrl = reader.result;
        var base64 = dataUrl.split(',')[1];
        callback(base64);
    };
    reader.readAsDataURL(blob);
};

回答by zinsat

var audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;

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

回答by A W

So the problem is that you want to upload a base 64 image and you have a blob url. Now the answer that will work on all html 5 browsers is: Do:

所以问题是你想上传一个 base 64 图像并且你有一个 blob url。现在适用于所有 html 5 浏览器的答案是:做:

  var fileInput = document.getElementById('myFileInputTag');
  var preview = document.getElementById('myImgTag');

  fileInput.addEventListener('change', function (e) {
      var url = URL.createObjectURL(e.target.files[0]);
      preview.setAttribute('src', url);
  });
function Upload()
{
     // preview can be image object or image element
     var myCanvas = document.getElementById('MyCanvas');
     var ctx = myCanvas.getContext('2d');
     ctx.drawImage(preview, 0,0);
     var base64Str = myCanvas.toDataURL();
     $.ajax({
         url: '/PathToServer',
         method: 'POST',
         data: {
             imageString: base64Str
         },
     success: function(data) { if(data && data.Success) {}},
     error: function(a,b,c){alert(c);}
     });
 }

回答by Ali Sadri

you can fix problem by:

您可以通过以下方式解决问题:

var canvas = $('#canvas'); 
var b64Text = canvas.toDataURL();
b64Text = b64Text.replace('data:image/png;base64,','');
var base64Data = b64Text;

I hope this help you

我希望这对你有帮助

回答by Valen

function bufferToBinaryString(arrayBuffer){
    return String.fromCharCode(...new Uint8Array(arrayBuffer));
}
(async () => console.log(btoa(bufferToBinaryString(await new Response(blob).arrayBuffer()))))();

or

或者

function bufferToBinaryString(arrayBuffer){
    return String.fromCharCode(...new Uint8Array(arrayBuffer));
}
new Response(blob).arrayBuffer().then(arr_buf => console.log(btoa(bufferToBinaryString(arr_buf)))))

see Response's constructor, you can turn [blob, buffer source form data, readable stream, etc.]into Response, which can then be turned into [json, text, array buffer, blob]with async method/callbacks.

参见Response 的构造函数,您可以将其[blob, buffer source form data, readable stream, etc.]转换为Response,然后可以将其转换[json, text, array buffer, blob]为异步方法/回调。

edit: as @Ralph mentioned, turning everything into utf-8 string causes problems (unfortunately Response API doesn't provide a way converting to binary string), so array bufferis use as intermediate instead, which requires two more steps (converting it to byte array THEN to binary string), if you insist on using native btoamethod.

编辑:正如@Ralph 提到的,将所有内容转换为 utf-8 字符串会导致问题(不幸的是,响应 API 没有提供转换为二进制字符串的方法),因此使用数组缓冲区作为中间值,这需要另外两个步骤(将其转换为字节数组 THEN 到二进制字符串),如果你坚持使用本机btoa方法。

回答by AmerllicA

There is a pure JavaSript way that is not depended on any stacks:

有一种不依赖于任何堆栈的纯 JavaSript 方式:

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

For using this helper function you should set a callback, example:

要使用此辅助函数,您应该设置一个回调,例如:

blobToBase64(blobData).then(res => {
  // do what you wanna do
  console.log(res); // res is base64 now
});


I write this helper function for my problem on React Native project, I wanted to download an image and then store it as a cached image:

我为 React Native 项目中的问题编写了这个辅助函数,我想下载一个图像,然后将其存储为缓存图像:

fetch(imageAddressAsStringValue)
  .then(res => res.blob())
  .then(blobToBase64)
  .then(finalResult => { 
    storeOnMyLocalDatabse(finalResult);
  });

回答by Vishnu IT

Most easiest way in a single line of code

单行代码中最简单的方法

var base64Image = new Buffer( blob, 'binary' ).toString('base64');

var base64Image = new Buffer( blob, 'binary' ).toString('base64');