gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:10:00 29 4
gpt4 key购买 nike

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

最佳答案

README.md说:

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

还有 sources indicate it supports several types ,如 StreamBufferBlob... 并且还会尝试将其他类型强制转换为 String

下面的代码片段显示了 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);
});

这里是foo.txt:

hello world!
how do you do?

注意:http://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 library)
  • 不要在选项中传递 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--

关于node.js - 如何在请求 Node 获取或 Node 中发送文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44021538/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com