Reputation: 1159
I have a backend endpoint that only accepts a json file. The user is supposed to upload a Json file and then the application submits this file to the endpoint and it works fine. Now I would like to use the same endpoint to upload json files created by the code, I would like for example to take the following javascript object
{
name: 'Brian',
age: 40
}
and transform it into a File object, so that I can submit it as a file, not as an object. I have tried to use the File Api constructor like this:
new File([{ name: 'Brian', age: 40 }], "file.json", { type: "application/json" });
but the endpoint does not accept it, I assume the first argument is not in the right format... should it be a blob instead?
Upvotes: 6
Views: 4651
Reputation: 718
const jsn = JSON.stringify(YOUR_OBJECT);
const blob = new Blob([jsn], { type: 'application/json' });
const file = new File([ blob ], 'file.json');
Upvotes: 10