在节点JS的REST API中将json对象上传为文件流

问题描述:

我有一个非常大的JSON对象,我想通过REST API将该对象作为JSON文件上传.

I have JSON object which is really big, I would like to upload this object as JSON file through REST API.

我试图在本地文件系统中写入json对象,然后从文件创建读取流并将其上传.但是我有一个限制,即我不应该在本地创建文件,我想像其他任何文件一样将json对象直接上传到REST api.

I tried to write the json object in local file system then created read stream from the file and uploaded it. But I have a limitation that I shouldn't create a file locally, I would like to upload the json object directly to the REST api as like any other file.

是否可以将json对象作为流发送到REST API中

Is it possible to send json object as stream into REST API

使用要发送的JSON对象创建一个新的BLOB,然后使用FormData将其作为文件发送出去.

Create a new BLOB with the JSON object that you want to send, and then use FormData to send it across as a file.

var formData = new FormData();
var blob = new Blob(['{"hello": "world!!!"}'], { type: 'text/json' });
formData.append('file', blob,'my_file.json');

然后将其作为POST请求发送出去.

And then send it across as a POST request.

fetch('http://URLgoesHere',
{ method: 'POST', body: formData,})
.then(console.log("works!"))
.catch((err) => console.log(err));

如果您尝试在服务器端执行此操作,则直接发送JSON对象可能会更容易,当在客户端接收到该对象时,只需使用JSON数据创建一个blob并将其下载为文本文件即可.

If you are trying to do this serverside, it's probably easier to just send the JSON object directly, and when received at client side, just create a blob with the JSON data and download it as a text file.