英文:
Get DataURL from Blob with await
问题
我有获取的结果,我想将其转换为一个类型为DataURL的对象。
我希望在我的应用主线中使用await
,而不是回调。
英文:
I have fetch results that I want to turn into a typed DataURL.
I want to use await
in the mainline of my app, not callbacks.
答案1
得分: 1
获取Blob数据的Data URL
/*
* getDataUrlFromBlob
* 可选:添加内容类型
*/
async function getDataUrlFromBlob(blob, contentType) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = (event) => {
const data = event.target.result;
resolve(data);
};
if (contentType) {
blob = new Blob([blob], {type: contentType}); // 添加类型
}
reader.readAsDataURL(blob);
});
}
示例用法
let response = await fetch(url, {method: "GET", mode: "cors"});
if (response && response.ok) {
const contentType = response.headers.get('Content-Type');
const blob = await response.blob();
const dataUrl = await getDataUrlFromBlob(blob, contentType)
return dataUrl;
}
注意:此处的代码已被翻译成中文。
英文:
function getDataUrlFromBlob
/*
* getDataUrlFromBlob
* Optional: adds content type
*/
async function getDataUrlFromBlob(blob, contentType) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = (event) => {
const data = event.target.result;
resolve(data);
};
if (contentType) {
blob = new Blob([blob], {type: contentType}); // add the type
}
reader.readAsDataURL(blob);
});
}
Example usage
let response = await fetch(url, {method: "GET", mode: "cors"});
if (response && response.ok) {
const contentType = response.headers.get('Content-Type');
const blob = await response.blob();
const dataUrl = await getDataUrlFromBlob(blob, contentType)
return dataUrl;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论