POST an image in JSON using Node.js

4.5k Views Asked by At

I need to post a file in Node.js using Request module in a JSON in such a pattern:

{
                id: <string>,
                title:<string>,
                file: file
}

The id and title are given, however I don' t know how to fill in the 3rd attribute 'file'. Let me also add, that the file is of graphical type, mostly .png, .jpg, and .tiff. Do you have any idea? The file has specified location on the disk, let it be for example /home/user/file.png

1

There are 1 best solutions below

3
ThatBrianDude On BEST ANSWER

You can always encode images into strings using any format you like.

Usually base64 should suffice.

var fs = require('fs');

// function to encode file data to base64 encoded string
function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');
}

Your JSON:

{

     id: someId,
     title: someTitle,
     file: base64_encode('your_file.any');

}