我有一种情况,我正在将 blobURL 转换为 base64 dataURL,但我只想在 url 是 blobURL 时执行此操作。
那么有什么方法可以检查它是否是有效的 blob url?
我的 blob url - blob:http://192.168.0.136/85017e84-0f2d-4791-b563-240794abdcbf
最佳答案
你正面临一个x-y problem .
您绝对不需要检查您的 blobURI 是否有效,因为您绝对不需要使用 blobURI 来创建它所指向的 Blob 的 base64 版本。
做到这一点的唯一方法是获取 Blob,这意味着在内存中创建其数据的副本是没有好处的。
您需要的是一种检索此 Blob 的方法。
不幸的是,没有正式的方法可以使用 Web API 做到这一点,但我们自己制作它并不难:
我们只需覆盖默认的 URL.createObjectURL
方法,以便使用 blobURI 作为键将传递的 Blob 映射到字典中:
(() => {
// overrides URL methods to be able to retrieve the original blobs later on
const old_create = URL.createObjectURL;
const old_revoke = URL.revokeObjectURL;
Object.defineProperty(URL, 'createObjectURL', {
get: () => storeAndCreate
});
Object.defineProperty(URL, 'revokeObjectURL', {
get: () => forgetAndRevoke
});
Object.defineProperty(URL, 'getBlobFromObjectURL', {
get: () => getBlob
});
const dict = {};
function storeAndCreate(blob) {
var url = old_create(blob); // let it throw if it has to
dict[url] = blob;
return url
}
function forgetAndRevoke(url) {
old_revoke(url);
// some checks just because it's what the question titel asks for, and well to avoid deleting bad things
try {
if(new URL(url).protocol === 'blob:')
delete dict[url];
}catch(e){} // avoided deleting some bad thing ;)
}
function getBlob(url) {
return dict[url];
}
})();
// a few example uses
const blob = new Blob(['foo bar']);
// first normal use everyhting is alive
const url = URL.createObjectURL(blob);
const retrieved = URL.getBlobFromObjectURL(url);
console.log('retrieved: ', retrieved);
console.log('is same object: ', retrieved === blob);
// a revoked URL, of no use anymore
const revoked = URL.createObjectURL(blob);
URL.revokeObjectURL(revoked);
console.log('revoked: ', URL.getBlobFromObjectURL(revoked));
// an https:// URL
console.log('https: ', URL.getBlobFromObjectURL(location.href));
<子>
PS:对于那些担心 Blob 可能被关闭的情况(例如,用户提供的文件已从磁盘中删除)的人,只需监听您将在下一步中使用的 FileReader 的 onerror
事件。
关于javascript - 如何使用javascript检查它是否是一个blob url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49145422/