如何使用JavaScript检查是否为Blob URL

5

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

那么有没有办法检查它是否是有效的blob url呢?

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

2个回答

6
你可以做类似以下的操作:
 var url = 'blob:http://192.168.0.136/85017e84-0f2d-4791-b563-240794abdcbf';

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

您也可以使用基于正则表达式的检查方法,例如:url.match('url expression')


6

您面临的是x-y问题

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接