Reputation: 519
I want to download and save a file from an api. The name of my file is text.txt
but the saved file is called: _text.txt_
and the content of this file is: [object Object]
This is my function to download as file:
const options = {
headers: new HttpHeaders().append('Authorization', this.oAuthService.getAccessToken()),
params: new HttpParams().append('responseType', 'text'),
observe: 'response' as 'response'
}
return this.http.get(this.fileServerUrl + 'file/download/' + filename + '/' + version, options)
.subscribe(
resp => { this.saveToFileSystem(resp)
});
}
private saveToFileSystem(response) {
const contentDispositionHeader: string = response.headers.get('Disposition');
const parts: string[] = contentDispositionHeader.split(';');
const filename = parts[1].split('=')[1];
filename.replace(/"/g, '');
console.log(filename);
console.log(response.body)
const blob = new Blob([response.body], { type: 'text/plain' });
saveAs(blob, filename);
}
the output of the first console.log is text.txt and the console.log of the response.body is: this is a test text..
so why is the saved file name with _ at the begin and end and the content not the text from the response body.
Thanks in advnace
Upvotes: 4
Views: 3545
Reputation: 1208
Try this:
const blob = new Blob([JSON.stringify(response.body)], { type: 'text/plain' });
And for _text.txt_
:
String is immutable type. So filename.replace... will not change filename value, it's returns new value.
You have to create new variable:
const newFileName = filename.replace(/"/g, '');
...
saveAs(blob, newFileName);
or just put filename.replace(/"/g, '')
into saveAs
saveAs(blob, filename.replace(/"/g, ''));
Upvotes: 3