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.

1 Answer 1

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/"))
Sign up to request clarification or add additional context in comments.

4 Comments

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.
@DonghuaLiu you would have to intercept the link click, and do the decoding on your own and then use it as you please.
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.
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*/});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.