node.js - How to post files in node?
phpcn_u1582
phpcn_u1582 2017-07-03 11:42:53
0
1
1317

I want to use node to call an API interface, and the interface parameters require uploading files. How to use the request module to achieve this operation? Ask God. .
The current code is as follows:
var config = require('./config');
var request = require('request');

var fs = require('fs');

var url = config.host '/inpidual/doc/ocr';

var file = fs.createReadStream('./WechatIMG5.jpeg');

var options = {

url: url,
method: 'POST',
"rejectUnauthorized": false,
form: {
    'agent_key': config.agent_key,
    'agent_no': config.agent_no,
    'doc_type': 'CHN_ID',
    'img': file,
    // 'has_oss_key': '1'
}

};

request(options, function (error, response, body) {

if (!error && response.statusCode == 200) {
    console.log(body);
    // console.log(error);
}

});

phpcn_u1582
phpcn_u1582

reply all(1)
代言

The file needs to use formData instead of form:

var options = {
    url: url,
    method: 'POST',
    formData: {
        'img': {
            value: fs.createReadStream('./WechatIMG5.jpeg')
        },
    }
};

Please note that the content-type in the header is different for different transmission methods. For files, it is multipart/form-data; for ordinary key-value pairs, it is application/x-www-form-urlencoded; for data in json format, it is application/json .

Please read the official documentation carefully. In request, form corresponds to application/x-www-form-urlencoded and formData corresponds to multipart/form-data.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template