Upload json object as file stream in REST API in node JS

感情迁移 提交于 2021-01-29 07:26:03

问题


I have JSON object which is really big, I would like to upload this object as JSON file through 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.

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


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/54559248/upload-json-object-as-file-stream-in-rest-api-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!