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