我有一种情况,我将 blobURL 转换为 base64 dataURL,但只有当 url 是 blobURL 时我才想这样做。
那么有什么方法可以检查它是否是有效的blob url?
我的 blob 网址 - blob:http://192.168.0.136/85017e84-0f2d-4791-b563-240794abdcbf
您绝对不需要检查您的 blobURI 是否有效,因为您绝对不需要使用 blobURI 来创建它所指向的 Blob 的 base64 版本。
这样做的唯一方法是获取 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));Run Code Online (Sandbox Code Playgroud)
PS:对于那些担心 Blob 可能被关闭的情况(例如,用户提供的文件已从磁盘中删除),那么只需侦听onerror您将在下一步中使用的 FileReader的事件。
你可以做类似的事情
var url = 'blob:http://192.168.0.136/85017e84-0f2d-4791-b563-240794abdcbf';
if(url.search('blob:') == -1){
//do something
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用基于正则表达式的检查 url.match('url expression')