Home > Blockchain >  Convert binary image data received from the server to <img> without base64
Convert binary image data received from the server to <img> without base64

Time:04-20

Since there's no reliable way to add custom request headers to img src, I'm trying to download the image manually with ajax.

Here's the code:

const load = async () => {
  loaded.value = false

  try {
    const res = await axios.get(src.value, {
      headers: { 'X-Chat-Session': sessid }
    })

    console.log(res.data) // "����\u0002IExif\u0000\u0000MM\u0000*\u0000\u0000\u0000\u0008\u0000\u0007\u0001\u0000\u0000\u0003\u0000\u0000\u0000... 

    loaded.value = true
    emit('loaded')
  } catch (e) {
    emit('loadingError', e)
  }
}

What I want to do is

<my image container>.appendChild(new Image(res.data))

It would be even better though if I could put the binary response into the src attribute of an already existing <img> element.

Please keep in mind that

  • Server side is not controlled by me
  • Service workers cannot be used
  • Base64 operations are highly undesirable

That's it. Thanks.

CodePudding user response:

Try this:

const load = async () => {
  loaded.value = false

  try {
    const res = await axios.get(src.value, {
      responseType: 'blob', 
      headers: { 'X-Chat-Session': sessid }
    })

    console.log(res.data)
    const url = URL.createObjectURL(res.data)
    <image element>.src = url;

    loaded.value = true
    emit('loaded')
  } catch (e) {
    emit('loadingError', e)
  }
}
  • Related