I learned that the body of a response of an HTTP message can be an arbitrary sequence of bytes so it doesn't need to be text/string. I guess that means when we need to transfer any binary files e.g. images / audio files over HTTP and we don't necessarily need to encode them into text/string using methods like base64, instead, we can just transfer them directly (of course with some compression e.g. gzip)
My first question is, I have not encountered any situations where I need to get actual images or other files via an API call e.g. a REST API call, instead normally we just get the URL to where the image is hosted and we use that URL to display the image in the web page and that seems to be more efficient to me. So I wonder in what circumstances we would have to transfer the actual image file over HTTP?
My second question is, if we are transferring the actual binary data over HTTP, I was looking at this and this
and I found that there seems to be two ways to handle the response: 1. read the response as blob
by response.blob()
2. read the response as arraybuffer
by response.arrayBuffer()
. I don't know what the differences are here. What determines whether or not we need to use blob
or arraybuffer
? Please refer to the below code snippet.
fetch(request, options).then((response) => {
response.arrayBuffer().then((buffer) => {
});
});
// differences?
fetch(request, options)..then(response => response.blob())
.then(images => {
})
My last question is, after we get the binary data either via response.blob()
or response.arrayBuffer()
, it seems like we still need to convert the binary data into string using window.btoa
i.e. base64 encoding and turn that into URL and then assign it to a img
element's src
attribute. I guess I don't understand why we would still have to convert the binary data into URL when we already have the data. Is that the only way to display an image in JavaScript, i.e. using src
attribute on img
tag? Also, according this this and this , I found there seems to be 2 ways to get the URL to a file: 1. converting the buffer to string using btoa
and then use data: URL
with that string 2. Use URL.createObjectURL
directly. Again, I wonder what the differences are here about these two different methods.