Using nodeJs with express.
The POST data is being parsed by body parser. Now i want to save the received image file in a folder of express application named images. The image is being posted to nodeJs app. When i look at the res.body variable in the callback function it contains the image, but i am confused how to save it.
I have looked on stackflow but could not find any answer. So posted myself.
I have tried using the fs library and its fs.writeFile() function. It saves the file but it is all corrupted.
image1 is the name of image in posted data. Using bodyparser()
var image = req.body.image1;
fs.writeFile('images/newImage.jpg', image, function(err){
if (err) throw err;
console.log('It is saved');
});
This saves a file in images directory but it is not the image.
I am using curl to post data to the nodejs application, the code is
$curl = curl_init();
$data = array('name' => 'First','file' => "image1=@".__dir__."/images/1.jpg");
curl_setopt($curl, CURLOPT_URL, "http://localhost:3000/api/");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_exec($curl);
curl_close($curl);
I am logging both of the two console.log functions
console.log(req.files);
console.log(req.body);
and the log give
{}
{ name: 'First',
file: 'image1=@C:\\xampp\\htdocs\\curltest/images/1.jpg' }
Please help this is driving me crazy :-/