简体   繁体   中英

I want to send Buffer Object as response from API

I have an image file that is created on my backend(node) and I am trying to send that to the front end to display. I'm not exactly sure how to manage the data but when I console the variable that's holding the file I get this:

Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e2 02 28 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 ...

I'm making a GET request from the front end and I want to be able to grab the image that's created and then displayed on the frontend. Is something like this possible?

The other option I've come up is to use a database to store the file but I'm trying to avoid a db.

Try to use this command

res.contentType('image/jpeg');
res.send(Buffer.from(data, 'binary'))
  1. Convert Buffer Object to Base64:
const bufferToBase64 = Buffer.from("Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e2 02 28 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 ...").toString('base64')
console.log(bufferToBase64)

Napkin (backend): https://www.napkin.io/n/4da91d59f9b443c8

  1. Put String in src attribute of img tag:
<img id="image" src="" />
fetch('https://napkinhq.npkn.net/buffer-object')
  .then(response => response.json())
  .then(data => {
    console.log(data.message)
    document.getElementById('image').src = `data:image/png;base64, ${data.message}`
});

CodePen (frontend): https://codepen.io/thomaswang/pen/oNWEmax?editors=1010

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