简体   繁体   中英

Loading image with XHR without responseType set to blob

I have this situation in which I load an image with XMLHttpRequest but without setting responseType to blob. So I receive a string

在此处输入图像描述

My question is, is it still possible to render the image in this situation?

I tried, for example, to convert this string to a Blob

out = new Blob([imageString],  { type: 'image/png' });

but this doesn't render the expected image. Any suggestions?

DEMO

And here is how my node backend sends that image to the browser

app.get("/binary/*", (req: express.Request, res: express.Response) => {
  const file = binaryPath + '/test.jpg';
  res.sendFile(file);
});

Finally got it: If you do not want to have xhr.responseType = 'blob' and you want to create a url from received data, then you need to set xhr.responseType = 'arraybuffer' . This allows to convert the binary xhr.response into a blob and then create a URL.createObjectURL .

The point is that when you do not set responseType to a binary type then you get the default xhr.responseType = 'text' and utf8 encoding. And then blob creation fails.

I have included this solution in your stackblitz .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM