In a webapp I'm doing, there are jsonarray files that are created. For example, they look like:
[{attr1:"123",attr2:"456"},{attr1:"abc",attr2:"def"}]
I am trying to send these jsonarray files to the client and they should be downloaded exactly as they in the server, they should not be opened or parsed.
In express I have tried using, send
, sendFile
and download
res.setHeader('Content-Type', 'application/json');
res.setHeader('Content-Disposition', 'attachment; filename=file.json');
res.sendFile(name, function (err) {
if (err) {
console.log('error sending:', name, err);
} else {
console.log('Sent:', name);
}
});
in the front end I am using file-saver
this.Service.get(filename).subscribe(
result => {
console.log(result)
let blob = new Blob(result, {type: "application/json"});
saveAs(blob, collectionname ".json");
}
);
and when i open the file in the client it looks like this:
[object Object][object Object]
But then I console.log() the result, I see the json objects.
What can I do?
Versions of my setup: Angular CLI: 12.0.5 Node: 14.16.1 Package Manager: npm 7.11.1 Angular: 12.0.5
CodePudding user response:
Blob cannot take json objects as argument (not even array of json objects). You could pass an array of strings, e.g.
new Blob(result.map(x=>JSON.stringify(x)), {type: "application/text"});
Raed the Blob documentation for details.