【发布时间】:2018-03-07 16:23:42
【问题描述】:
我有一种将 blobURL 转换为 base64 dataURLs 的情况,但我只想在 url 是 blobURL 时这样做。
那么有没有办法检查它是否是有效的blob url?
我的 Blob 网址 - blob:http://192.168.0.136/85017e84-0f2d-4791-b563-240794abdcbf
【问题讨论】:
标签: javascript jquery
我有一种将 blobURL 转换为 base64 dataURLs 的情况,但我只想在 url 是 blobURL 时这样做。
那么有没有办法检查它是否是有效的blob url?
我的 Blob 网址 - blob:http://192.168.0.136/85017e84-0f2d-4791-b563-240794abdcbf
【问题讨论】:
标签: javascript jquery
您绝对不需要检查您的 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));
PS:对于那些担心 Blob 可能被关闭的情况(例如,用户提供的文件已从磁盘中删除)然后只需侦听您将在下一步中使用的 FileReader 的 onerror 事件。
【讨论】:
你可以做类似的事情
var url = 'blob:http://192.168.0.136/85017e84-0f2d-4791-b563-240794abdcbf';
if(url.search('blob:') == -1){
//do something
}
您也可以对url.match('url expression') 使用基于正则表达式的检查
【讨论】: