Issue
I have an http get request that retrieve from backend a txt file as attached. The response arrives correctly with correct data, but the txt attached downloaded has incorrect value : [object Object]. The code in the success block is:
var file = new Blob([data],{type: "text/plain"}); // data here contains correctly the values
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = idUser+'.txt';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
What's the correct way to see in the downloaded file the txt content?
thanks
Solution
Whenever you see a object unexpectedly transforming into "[object Object]"
in JavaScript, it usually means that somewhere along the way, something that expected a string has implicitly typecast your object into one (the result of which is "[object Object]"
).
In this case, it's because the Blob constructor (as documented here) expected an array of USVStrings, not an array of objects. So to properly stringify your object, rewrite your first line to:
var file = new Blob([JSON.stringify(data)],{type: "text/plain"});
That should solve your issue, but just as an additional tip, if this file is supposed to be human-readable at some point, you may want to call JSON.stringify
with JSON.stringify(data, null, '\t')
to prettify the file (see the third parameter of the JSON.stringify documentation for details).
Answered By - user3781737
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.