Reputation: 13
I'm trying to translate my REST-webserver from PHP to Express.js / Node.js.
There is an request which contains an image encoded by Androids Base64 library:
ByteArrayOutputStream bAOS = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, bAOS);
params.put("image", Base64.encodeToString(bAOS.toByteArray(), Base64.DEFAULT));
On server-side it should simply decode the data and save the image to a directory. For example, I tried it the following way, using the "base-64" npm-package (https://www.npmjs.com/package/base-64):
const image = req.body['image'];
const decodedData = this.base64.decode(image);
this.fs.writeFileSync(PICTURES_PATH + 'image.png', decodedData);
But it doesn't seem to decode well, I can't view the file and its size is way to small. This wasn't my only attempt, I tried using Node.js-buffers or another package called "base64-img" (https://www.npmjs.com/package/base64-img). The last one worked for test-requests I sent with Postman, but couldn't handle data sent by the app. The console shows the Android-app does not send "data:image/png;base64,..." at beginning, which causes base64-img to fail.
In PHP i just did sth. like:
$decodedImage=base64_decode("$image");
file_put_contents("pictures/".$name.".PNG", $decodedImage);
Which was working. I want the app to continue working without updating it, so I need to fix it server-side.
Can somebody help me with that? Thanks guys!
Upvotes: 0
Views: 884
Reputation: 3627
You don't need to use any library, its all in nodejs.
const image = req.body['image']; const decodedData = new Buffer(image, 'base64'); fs.writeFileSync(PICTURES_PATH + 'image.png', decodedData);
Upvotes: 1