如何使用JavaScript检查它是否是Blob网址 [英] How to check whether it is a blob url using javascript
问题描述
我遇到将blobURL转换为base64 dataURLs的情况,但是仅在url为blobURL的情况下才想这样做.
I have a situation where I am converting blobURL to base64 dataURLs, but I want to do this only if url is a blobURL.
那么有什么方法可以检查它是否是有效的Blob网址?
So is there any way to check whether it is valid blob url?
我的Blob网址-blob:http://192.168.0.136/85017e84-0f2d-4791-b563-240794abdcbf
推荐答案
您正面临 xy问题.
您绝对不需要检查您的blobURI是否有效,因为您绝对不需要使用blobURI来创建它所指向的Blob的base64版本.
You are facing an x-y problem.
You absolutely don't need to check if your blobURI is a valid one, because you absolutely don't need to use the blobURI in order to create a base64 version of the Blob it's pointing to.
唯一的方法是获取Blob,这意味着在内存中创建其数据的副本是徒劳的.
The only way to do it is to fetch the Blob and this means creating a copy of its data in memory for no-good.
不幸的是,使用Web API并没有官方的方法,但是我们自己做起来并不难:
There is unfortunately no official way to do so with the web APIs, but it's not that hard to make it ourselves:
我们只需覆盖默认的URL.createObjectURL
方法,即可使用blobURI作为键将传递的Blob映射到字典中.
We simply have to overwrite the default URL.createObjectURL
method in order to map the passed Blob in a dictionnary using the blobURI as key:
(() => {
// 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
事件.
PS: for the ones concerned about the case a Blob might be closed (e.g user provided file has been deleted from disk) then simply listen for the onerror
event of the FileReader you'd use in next step.
这篇关于如何使用JavaScript检查它是否是Blob网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!