繁体   English   中英

如何使用javascript检查它是否是blob url

[英]How to check whether it is a blob url using javascript

我有一种情况,我将blobURL转换为base64 dataURLs,但我想只在url是blobURL时才这样做。

那么有什么方法可以检查它是否是有效的blob url?

我的blob网址 - blob:http://192.168.0.136/85017e84-0f2d-4791-b563-240794abdcbf

你正面临一个xy问题

你绝对不需要检查你的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事件。

你可以做点什么

 var url = 'blob:http://192.168.0.136/85017e84-0f2d-4791-b563-240794abdcbf';

 if(url.search('blob:') == -1){
   //do something
 }

你也可以使用基于reg-expression的检查和url.match('url expression')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM