0

I store images im mongoDB like this:

img: {
  contentType: "image/png"
  data: {
    data: Array(135239),
    type: "Buffer"
  }
}

Then i got them on frontend and trying to use in html img tag, but there are no pictures I have tried to transform the data to

let blob = new Blob([img.data], {type : img.contentType})
let img = document.createElement('img').setAttribute('src', URL.createObjectURL(blob))
let container = document.getElementById('container')
container.appendChild(img)

or

let img = document.createElement('img').setAttribute('src', `data:${img.contentType};base64,${img.data}`)
let container = document.getElementById('container')
container.appendChild(img)

but none of it does not seem to work

P.S. In the guide was written i should transform img.data.toString('base64'), but it does not work too

  • @Sean just a typo, it shoud be img.data.data then `cause if i remove brackets, i`ll get TypeError: Failed to construct 'Blob': The object must have a callable @@iterator property., but anyways, it should be img.data.data, still does not work – DoloreMentale Dec 04 '20 at 23:27
  • Does this answer your question? [Convert Blob to image url and use in image src to display image](https://stackoverflow.com/questions/51019467/convert-blob-to-image-url-and-use-in-image-src-to-display-image) – Salmen Bejaoui Dec 05 '20 at 00:27
  • @SalmenBejaoui unfortunately nope, but i found another one post thanks to yours – DoloreMentale Dec 05 '20 at 06:54

1 Answers1

0

If you have the same issue, just check wether you use this guide: https://www.geeksforgeeks.org/upload-and-retrieve-image-on-mongodb-using-mongoose/ if so, just do the same as here:

function toBase64(arr) {
   arr = new Uint8Array(arr) if it's an ArrayBuffer
   return btoa(
      arr.reduce((data, byte) => data + String.fromCharCode(byte), '')
   );
}
  • 1
    A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted.](/help/deleted-answers) – Sabito stands with Ukraine Dec 05 '20 at 07:54