如何在请求node-fetch或nodejs中发送文件

如何在nodejs / node-fetch POST请求中附加文件。我想要调用一个导入文件(.xls或csv)的API。 我如何使用Node-fetch / nodejs来做到这一点。

README.md说:

在请求和响应中使用本机stream。

来源表明它支持几种types ,如StreamBufferBlob …,也会试图强制为其他types的String

下面的片段显示了3个例子,所有的工作,与v1.7.1或2.0.0-alpha5(另见FormData其他例子与FormData ):

 let fetch = require('node-fetch'); let fs = require('fs'); const stats = fs.statSync("foo.txt"); const fileSizeInBytes = stats.size; // You can pass any of the 3 objects below as body let readStream = fs.createReadStream('foo.txt'); //var stringContent = fs.readFileSync('foo.txt', 'utf8'); //var bufferContent = fs.readFileSync('foo.txt'); fetch('http://httpbin.org/post', { method: 'POST', headers: { "Content-length": fileSizeInBytes }, body: readStream // Here, stringContent or bufferContent would also work }) .then(function(res) { return res.json(); }).then(function(json) { console.log(json); }); 

这里是foo.txt

 hello world! how do you do? 

注意: http://httpbin.org/posthttp://httpbin.org/post用JSON回复,其中包含发送请求的详细信息。

结果:

 { "args": {}, "data": "hello world!\nhow do you do?\n", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip,deflate", "Connection": "close", "Content-Length": "28", "Host": "httpbin.org", "User-Agent": "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)" }, "json": null, "origin": "86.247.18.156", "url": "http://httpbin.org/post" } 

如果您需要将文件作为具有更多参数的表单的一部分发送,则可以尝试:

  • npm install form-data
  • 传递一个FormData对象作为body( FormData是一种Stream ,通过CombinedStream 库 )
  • 不要在选项中传递header (不像上面的例子)

然后这工作:

 const formData = new FormData(); formData.append('file', fs.createReadStream('foo.txt')); formData.append('blah', 42); fetch('http://httpbin.org/post', { method: 'POST', body: formData }) 

结果(只显示发送的内容):

 ----------------------------802616704485543852140629 Content-Disposition: form-data; name="file"; filename="foo.txt" Content-Type: text/plain hello world! how do you do? ----------------------------802616704485543852140629 Content-Disposition: form-data; name="blah" 42 ----------------------------802616704485543852140629-- 

这是一个将本地文件stream式传输到响应的快速服务器。

 var fs = require('fs'); var express = require('express')(); express.get('/',function(req,res){ var readStream = fs.createReadStream('./package.json'); readStream.pipe(res); }) express.listen(2000); 
Interesting Posts