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 Answer 1

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

}
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
OK, right now I know what encoding should it be: form/multipart

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.