最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to upload a file using a rest client for node - Stack Overflow

programmeradmin2浏览0评论

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 service. The npm package that I use is: . If there are other rest clients, I can use those as well. The rest api I need to use is described below:

POST    /         ; Uploads a new PDF document via a form <br>
POST    /file     ; Uploads a new PDF document via bytestream

The question is how to upload the file. Also, I would like to see how to store the file at the other end.

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 service. The npm package that I use is: https://www.npmjs.com/package/node-rest-client. If there are other rest clients, I can use those as well. The rest api I need to use is described below:

POST    /         ; Uploads a new PDF document via a form <br>
POST    /file     ; Uploads a new PDF document via bytestream

The question is how to upload the file. Also, I would like to see how to store the file at the other end.

Share Improve this question edited Jul 10, 2015 at 13:18 Andrei asked Jun 30, 2015 at 23:54 AndreiAndrei 7,6078 gold badges36 silver badges64 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 12 +50

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

You can use request.

There is an example for that

fs.createReadStream('file.pdf').pipe(request.post('http://example.com/file'))
发布评论

评论列表(0)

  1. 暂无评论