这是我想要Blob
到Base64
字符串代码的代码段:
这个评论的部分有效,当由此生成的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);
问题在于代码越低,生成的源变量为null
更新:
使用JQuery是否有更简单的方法可以从Blob文件创建Base64字符串,如上面的代码所示?
答案 0 :(得分:193)
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
base64data = reader.result;
console.log(base64data);
}
将docs readAsDataURL
个编码格式化为base64
答案 1 :(得分:21)
这对我有用:
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);
};
答案 2 :(得分:13)
有一种不依赖任何堆栈的纯JavaSript方法:
const blobToBase64 = blob => {
const reader = new FileReader();
reader.readAsDataURL(blob);
return new Promise(resolve => {
reader.onloadend = () => {
resolve(reader.result);
};
});
};
要使用此辅助功能,您应该设置一个回调,例如:
blobToBase64(blobData).then(res => {
// do what you wanna do
console.log(res); // res is base64 now
});
我为React Native项目上的问题编写了此辅助函数,我想下载一个图像,然后将其存储为缓存的图像:
fetch(imageAddressAsStringValue)
.then(res => res.blob())
.then(blobToBase64)
.then(finalResult => {
storeOnMyLocalDatabase(finalResult);
});
答案 3 :(得分:4)
所以问题是你要上传一个基础64图像并且你有一个blob网址。现在,适用于所有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);}
});
}
答案 4 :(得分:3)
您可以通过以下方式解决问题:
var canvas = $('#canvas');
var b64Text = canvas.toDataURL();
b64Text = b64Text.replace('data:image/png;base64,','');
var base64Data = b64Text;
我希望这可以帮到你
答案 5 :(得分:3)
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);
}
答案 6 :(得分:3)
async function blobToBase64(blob) {
return new Promise((resolve, _) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
}
let blob = null; // <= your blob object goes here
blobToBase64(blob)
.then(base64String => console.log(base64String));
另见:
答案 7 :(得分:1)
单行代码中最简单的方法
var base64Image = new Buffer(blob,&#39; binary&#39;)。toString(&#39; base64&#39;);
答案 8 :(得分:1)
我想要一些可以访问base64值的东西来存储到列表中,并且对我来说添加事件侦听器是可行的。您只需要FileReader,它将读取图像Blob并在结果中返回base64。
createImageFromBlob(image: Blob) {
const reader = new FileReader();
const supportedImages = []; // you can also refer to some global variable
reader.addEventListener(
'load',
() => {
// reader.result will have the required base64 image
const base64data = reader.result;
supportedImages.push(base64data); // this can be a reference to global variable and store the value into that global list so as to use it in the other part
},
false
);
// The readAsDataURL method is used to read the contents of the specified Blob or File.
if (image) {
reader.readAsDataURL(image);
}
}
最后一部分是readAsDataURL,它非常重要,可用于读取指定Blob的内容
答案 9 :(得分:0)
(async () => console.log(btoa(await new Response(blob).text())))();
或
new Response(blob).text().then(t => console.log(btoa(t)))
请参见Response's constructor,您可以将[blob, buffer source form data, readable stream, etc.]
转换为Response,然后可以将其转换为[json, text, array buffer, blob]
,从而使方法/回调异步。
答案 10 :(得分:0)
另一种方法是在返回FileReader
的{{1}}周围使用一个简单的包装器:
Observable
用法:
function toBase64(blob: Blob): Observable<string> {
const reader = new FileReader();
reader.readAsDataURL(blob);
return fromEvent(reader, 'load')
.pipe(map(() => (reader.result as string).split(',')[1]));
}
答案 11 :(得分:0)
打字稿版本:
const blob2Base64 = (blob:Blob):Promise<string> => {
return new Promise<string> ((resolve,reject)=> {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => resolve(reader.result.toString());
reader.onerror = error => reject(error);
})
}
用法:
blob2Base64(blob).then(res=>console.log(res))
答案 12 :(得分:-1)
异步 TypeScript 变体:
async function blobToBase64Async(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onerror = (e) => reject(fileReader.error);
fileReader.onloadend = (e) => {
const dataUrl = fileReader.result as string;
// remove "data:mime/type;base64," prefix from data url
const base64 = dataUrl.substring(dataUrl.indexOf(',') + 1);
resolve(base64);
};
fileReader.readAsDataURL(blob);
});
}
示例用法:
async function fetchToBase64Async(url: string, init?: RequestInit): Promise<string> {
try {
const response = await fetch(url, init);
if (!response.ok) {
const responseText = await response.text();
throw new Error("server status: " + response.status + "\n" + "server response:" + "\n" + responseText);
}
const blob = await response.blob();
const base64 = await blobToBase64Async(blob);
return base64;
} catch (e) {
throw new Error("failed to fetch: " + url + "\n" + "caused by: " + e);
}
}
async function demoUsage() {
const base64 = await fetchToBase64Async("https://httpstat.us/200", {
method: "POST",
headers: {
"Accept": "*/*",
"Authorization": "Bearer ...",
}
});
console.log(base64);
}
注意事项:
load
而不是 loadend
事件readAsDataURL