node.js 如何在请求节点获取或节点中发送文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44021538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:13:34  来源:igfitidea点击:

How to send a file in request node-fetch or Node?

node.jsfilepostnode-fetch

提问by Rocky

How do I attach a file in Node or Node Fetch POST request? I am trying to invoke an API which will import a CSV or XLS file. Is this possible using Node or Node Fetch?

如何在 Node 或 Node Fetch POST 请求中附加文件?我正在尝试调用将导入 CSV 或 XLS 文件的 API。这可以使用 Node 或 Node Fetch 吗?

回答by Hugues M.

README.mdsays:

README.md说:

Use native stream for body, on both request and response.

在请求和响应中使用本机流作为正文。

And sources indicate it supports several types, like Stream, Buffer, Blob... and also will try to coerce as Stringfor other types.

并且消息来源表明它支持多种类型,例如Stream, Buffer, Blob... 并且也会像String其他类型一样尝试强制。

Below snippet shows 3 examples, all work, with v1.7.1 or 2.0.0-alpha5 (see also other example further down with FormData):

下面的代码片段显示了 3 个示例,所有示例均适用于 v1.7.1 或 2.0.0-alpha5(另请参阅下面的其他示例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);
});

Here is foo.txt:

这是foo.txt

hello world!
how do you do?

Note: http://httpbin.org/postreplies with JSON that contains details on request that was sent.

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

Result:

结果:

{
  "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"
}

If you need to send a file as part of a form with more parameters, you can try:

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

  • npm install form-data
  • pass a FormDataobject as body (FormDatais a kind of Stream, via CombinedStreamlibrary)
  • do not pass headerin the options (unlike examples above)
  • npm install form-data
  • FormData对象作为主体传递(FormData是一种Stream,通过CombinedStream
  • 不要传入header选项(与上面的示例不同)

and then this works:

然后这有效:

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

Result (just showing what is sent):

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

----------------------------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--

回答by Rico Kahler

I was looking for how to use node-fetchto upload files via multipart/form-dataand their GitHub docs actually shows how to do this. Below is modified example showing how to attach a buffer to FormDataand upload that.

我一直在寻找如何使用node-fetch通过上传文件multipart/form-data他们的 GitHub 文档实际上展示了如何做到这一点。下面是修改后的示例,显示了如何将缓冲区附加到FormData并上传它。

const FormData = require('form-data');     
const form = new FormData();

const buffer = // e.g. `fs.readFileSync('./fileLocation');
const fileName = 'test.txt';

form.append('file', buffer, {
  contentType: 'text/plain',
  name: 'file',
  filename: fileName,
});

fetch('https://httpbin.org/post', { method: 'POST', body: form })
    .then(res => res.json())
    .then(json => console.log(json));

Sharing this for anyone else who googled "node-fetch upload file multipart" like I did.

与像我一样在谷歌上搜索“node-fetch upload file multipart”的其他人分享这个。

回答by Naveen Kerati

This is a express server that streams a local file to the response.

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

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