How to upload a file using a rest client for node

前端 未结 2 1807
逝去的感伤
逝去的感伤 2021-02-05 08:20

I have a REST client on node, and I\'m trying to upload pdf a file to another REST webserver which provides the ability to parse my pdf and extract some data. Basically it is a

2条回答
  •  执念已碎
    2021-02-05 08:49

    You can use npm module request to upload the file. Here is a working example

    var request = require('request');
    var fs = require('fs');
    request({
      method: 'PUT',
      preambleCRLF: true,
      postambleCRLF: true,
      uri: 'http://yourdomain/file',
      multipart: [
        {
          'content-type': 'application/pdf',
          body: fs.createReadStream('image.png') 
        }
      ]    
    },
    function (error, response, body) {
      if (error) {
        return console.error('upload failed:', error);
      }
      console.log('Upload successful!  Server responded with:', body);
    });
    

    For receiving at the server side with node you can use modules like busboy. Here is a demo for this

    var busboy = require('connect-busboy');
    app.use(busboy());
    app.use(function(req, res) {
      if (req.busboy) {
        req.busboy.on('file', function(fieldname, file, filename, encoding,    mimetype) {
          // move your file etc
        });
        req.pipe(req.busboy);
      }
    });
    

提交回复
热议问题