Convert Buffer (image) to file

Issue

I’m looking for the best way to send image files to my server using Apollo Express, and Node.
Getting the information there doesn’t seem to be an issue, I convert the object into a string but can’t find out how to convert it back to a regular file object to store away.

What I have so far;

JS - let buffer = await toBase64(file);

Through Apollo server..

Node - let buffer = Buffer.from(args.image, 'base64');

This gives me a Buffer. I’m unsure how to proceed with NodeJS to convert this back to a file object.

Thanks

Solution

You can use one of the various write or writeFile methods which accept a Buffer.

const fs = require("fs");

let buffer = Buffer.from(
  "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAGCAIAAABxZ0isAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAQSURBVBhXY/iPAwygxP//AAjcj3EdtT3BAAAAAElFTkSuQmCC",
  "base64"
);

fs.writeFile("pic.png", buffer, (err) => {
  if (err) throw err;
  console.log("The file has been saved!");
});

Answered By – peterulb

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published