POST JSON 中的图像使用 Node.js

POST an image in JSON using Node.js

我需要 post Node.js 中的一个文件,使用 JSON 中的 Request 模块,格式如下:

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

给了id和title,但是不知道第三个属性怎么填'file'。我还要补充一点,该文件是图形类型的,主要是 .png、.jpg 和 .tiff。你有什么主意吗? 该文件在磁盘上指定了位置,例如 /home/user/file.png

您始终可以使用您喜欢的任何格式将图像编码为字符串。

通常 base64 就足够了。

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

你的JSON:

{

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

}