从 Blob 中使用 await 获取 DataURL

huangapple go评论63阅读模式
英文:

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;
}

huangapple
  • 本文由 发表于 2023年4月10日 22:14:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977868.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定