最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - I want to send Buffer Object as response from API - Stack Overflow

programmeradmin2浏览0评论

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 e up is to use a database to store the file but I'm trying to avoid a db.

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 e up is to use a database to store the file but I'm trying to avoid a db.

Share Improve this question asked Jul 27, 2021 at 5:40 Luis RodriguezLuis Rodriguez 2773 silver badges16 bronze badges 1
  • Why are you trying to avoid a DB? – Alex Mckay Commented Jul 27, 2021 at 5:52
Add a ment  | 

2 Answers 2

Reset to default 5

Try to use this mand

res.contentType('image/jpeg');
res.send(Buffer.from(data, 'binary'))
  1. Convert Buffer Object to Base64 in your backend:
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')
  1. Put String in src attribute of img tag:
<img id="image" src="" />
fetch(YOUR_BACKEND_URL)
  .then(response => response.json())
  .then(data => {
    document.getElementById('image').src = `data:image/png;base64, ${data.message}`
});
发布评论

评论列表(0)

  1. 暂无评论