javascripturlcreateobjecturl

Could not get the data in URL.createObjectURL


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.


Solution

  • 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/"))