2

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 Answers1

2

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');

}
ThatBrianDude
  • 2,952
  • 3
  • 16
  • 42
  • The thing is this JSON is used for API... Do you think this encoding won' t make a difference? or maybe I should find out what kind of 'file' does this API need? – Patryk Stroński Feb 02 '18 at 11:08
  • Yes you should definetly find out what the API expects. This is just a way to store the actual image data in a JSON compatible format which is literally just a string. – ThatBrianDude Feb 02 '18 at 11:13
  • OK, right now I know what encoding should it be: form/multipart – Patryk Stroński Feb 02 '18 at 15:11