feat: add `Get#dataUrl` to turn blob to data url.

This commit is contained in:
Rintim 2024-05-11 15:05:15 +08:00
parent eafa5e3f17
commit 863ca796b3
No known key found for this signature in database
GPG Key ID: BE9E1EA615BACFCF
1 changed files with 41 additions and 0 deletions

View File

@ -4809,6 +4809,47 @@ export class Get {
}
return base;
}
/**
* 通过`FileReader`将Blob转换成对应内容的[Data URL](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/Data_URLs)
*
* @param {Blob} blob - 需要转换的内容
* @returns {Promise<string>} 对应Blob内容的
*/
dataUrl(blob) {
return new Promise((resolve, reject) => {
let fileReader = new FileReader();
fileReader.onload = resolve;
fileReader.onerror = reject;
fileReader.readAsDataURL(blob);
}).then(event => event.target.result);
}
/**
* 通过`fetch`读取data URL的内容转换成Blob后返回生成的blob URL
*
* 该方法具有缓存同一data URL仅会返回同一blob URL
*
* 该方法相比`get.objectURL`会保留文件的类型
*
* ---
*
* > 其实我不确定`get.objectURL`是否有实际意义上的需求我也不确定`get.objectURL`不保留类型是否是刚需但既然原先就存在那么就不要动
*
* @async
* @param {string | URL} dataUrl - 需要转换的data URL
* @returns {Promise<URL>}
*/
async objectURLAsync(dataUrl) {
let dataString = dataUrl instanceof URL ? dataUrl.href : dataUrl;
const objectURLMap = lib.objectURL;
if (objectURLMap.has(dataString)) return new URL(objectURLMap.get(dataString));
let blob = await (await fetch(dataUrl)).blob();
const objectURL = URL.createObjectURL(blob);
objectURLMap.set(dataString, objectURL);
return new URL(objectURL);
}
}
export let get = new Get();