feat: add `Get#dataUrl` to turn blob to data url.
This commit is contained in:
parent
eafa5e3f17
commit
863ca796b3
|
@ -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();
|
||||
|
|
Loading…
Reference in New Issue