Convert base64 image to file in Node Js

I am new to Node Js. I need to enable a profile image for users. I get an image request in base64 from an iOS application. I need to save it in the image folder and save the image path in the mongodb database.

I used the following code,

var bitmap = new Buffer(req.body.profile_image, 'base64');
// write buffer to file
fs.writeFileSync("images/example.jpg", bitmap);

where req.body.profile_image is a base64 image.

I get the following error:

TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.

req.body.profile_image value will be,

+MZScHeJQ9Cz5dfxnEmIMHWMZyZYnYx8Rrhj0HbtfGUanv5w3UHUyADbiGsKJxeM1yV4uGwBS7cYlAec1w0AX6xg2A1O854UF8OS6PAP1MtzkeFnrNlD41U8XFeGrp1fn3jRMUs8sqS61umSS2rR2NDhppjZ4OvnOWBAq6X+sQNkhKkfZOdYsZOpz8fWIQb6wQ/GchVCgfZko4PMDg1DSumausG6o+2E6wKLLjKReUaHEQXKJV8h85XEKN4p/WEBvTHmmJ/IN178YJVgrGmfOScAuBPp+sggGA7/wC1kgbDiacbGABOcCLHVRpMuBQh5Xn4xqARF03pwkJT23LhxGLiSGp8mCVWDrzPf3iwp4C3nDSg2VUfNwgDvm6vrIiFJvp8ZHIdjoFx8BX0OH0+8TVii3GAKKc2kjz7dYqUCdsuMOm2hrr+h//Z

Please, help.

+2
source share
1 answer

Edit: this code worked for me. Perhaps the error will occur later.

var fs = require("fs");
var image = "+MZScHeJQ9Cz5dfxnEmIMHWMZyZYnYx8Rrhj0HbtfGUanv5w3UHUyADbiGsKJxeM1yV4uGwBS7cYlAec1w0AX6xg2A1O854UF8OS6PAP1MtzkeFnrNlD41U8XFeGrp1fn3jRMUs8sqS61umSS2rR2NDhppjZ4OvnOWBAq6X+sQNkhKkfZOdYsZOpz8fWIQb6wQ/GchVCgfZko4PMDg1DSumausG6o+2E6wKLLjKReUaHEQXKJV8h85XEKN4p/WEBvTHmmJ/IN178YJVgrGmfOScAuBPp+sggGA7/wC1kgbDiacbGABOcCLHVRpMuBQh5Xn4xqARF03pwkJT23LhxGLiSGp8mCVWDrzPf3iwp4C3nDSg2VUfNwgDvm6vrIiFJvp8ZHIdjoFx8BX0OH0+8TVii3GAKKc2kjz7dYqUCdsuMOm2hrr+h//Z";
var bitmap = new Buffer(image, 'base64');
fs.writeFileSync("images/example.jpg", bitmap);

If you said

console.log(req.body.profile_image) 

but not

 console.log(typeof req.body.profile_image)

, - req.body.profile_image, . , "typeof" , "typeof", , . , .

lolz:

Buffer.from(String.fromCharCode.apply(null, new Uint16Array(req.body.profile_image)), "base64")

req.body.profile_image?

writeFileSync , . , req.body.profile_image?

, , , 'new' . , Buffer.from(...) .

+4

Source: https://habr.com/ru/post/1606734/


All Articles