6

I am new to Node Js. I need to include a profile image for users. I get request of image in base64 from IOS app. I need to store it in images folder and save the image path in mongodb database.

I have 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 am getting 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.

rekha s
  • 567
  • 5
  • 7
  • 23
  • `fs.writeFileSync` doesn't return anything. It throws an Error object. So write `fs.writeFileSync(file, content, 'utf8'); ` within a try-catch. – Mohammad Sayeed Jun 03 '16 at 07:30

1 Answers1

11

Edit: This code worked for me. Maybe the error happens 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) 

rather than

 console.log(typeof req.body.profile_image)

It would cast what ever data is in req.body.profile_image to a string before printing. Its possible you just forgot the 'typeof' when commenting, but if you didn't add the 'typeof' you can't be certain that it contains a string. There's more than one constructor to Buffer and it may be using the wrong one.

For the lolz try:

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

What gets assigned to req.body.profile_image?

The first argument to writeFileSync is a string, so it can't be causing the type error. Can you be more specific as to what is contained in req.body.profile_image?

On a side note, although I think this is unrelated to your problem, instantiating a Buffer with the 'new' keyword is deprecated. Maybe using Buffer.from(...) will move you in the direction of a solution.

charlie_destwin
  • 146
  • 1
  • 3