search

Home  >  Q&A  >  body text

node.js - How to post files in node?

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_u1582phpcn_u15822787 days ago1379

reply all(1)I'll reply

  • 代言

    代言2017-07-03 11:44:53

    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.

    reply
    0
  • Cancelreply