3

I am just curious about how to get the data wrapped in URL.createObjectURL.

So I write the following code.

function typedArrayToURL(typedArray, mimeType) {
  return URL.createObjectURL(new Blob([typedArray.buffer], {type: mimeType}))
}
const bytes = Uint8Array.from("https://www.baidu.com/")
// const url = typedArrayToURL(bytes, 'text/html');
const url = typedArrayToURL(bytes, 'text/plain; charset=utf-8');

let blob = await (await fetch(url)).blob();
console.info(new Uint8Array(blob))

let ab = await (await fetch(url)).arrayBuffer();
console.info(new Uint8Array(ab))

The size of blob or ab 22 which is eqauls to the length of "https://www.baidu.com/", but the data in it is all zero.

Donghua Liu
  • 1,776
  • 2
  • 21
  • 30

1 Answers1

1

An intArray expects integers. So you will have to provide the data in the correct format.

So something like

const bytes = Uint8Array.from("https://www.baidu.com/".split('').map(v=>v.charCodeAt(0)));

or

const encoder = new TextEncoder();
const bytes = Uint8Array.from(encoder.encode("https://www.baidu.com/"))
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • Another question, can I set the `href` attribute of `a` to a `URL.createObjectURL` instance, and when I click the link then navigate to the url specified in `URL.createObjectURL` instance instead of download the content. – Donghua Liu Dec 22 '21 at 11:03
  • @DonghuaLiu you would have to intercept the link click, and do the decoding on your own and then use it as you please. – Gabriele Petrioli Dec 22 '21 at 12:44
  • Thanks for your helpful explaination, You mean I need to use `fetch` to get the data of `URL.createObjectURL` instance, then set it to the `href` attribute of `a`. So I should use `a.href = await (await fetch(objectURL)).text()` not `a.href = objectURL`. – Donghua Liu Dec 22 '21 at 15:11
  • I am not sure of what you are trying to do. If you can put the url directly in the href then why are you going through the whole `createObjectURL` part ? Otherwise i meant the you could do something like `document.querySelector('a[href^="blob:"]').addEventListener('click', function(e){e.preventDefault(); /* here you could use the e.target.href and decode the href to get the actual text url*/});` – Gabriele Petrioli Dec 22 '21 at 16:21