使用FileSaver和Blob将响应正文另存为文件 [英] Save a response body as file with FileSaver and blob
问题描述
我想从api下载并保存文件.我的文件名为text.txt
,但保存的文件名为:_text.txt_
,此文件的内容为:[object Object]
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);
}
第一个console.log的输出是text.txt,response.body的console.log是:这是一个测试文本.
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.
感谢前进
推荐答案
尝试一下:
const blob = new Blob([JSON.stringify(response.body)], { type: 'text/plain' });
对于_text.txt_
:
字符串是不可变的类型.所以filename.replace ...不会更改文件名的值,它会返回新值.
您必须创建新变量:
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);
或仅将filename.replace(/"/g, '')
放入saveAs
saveAs(blob, filename.replace(/"/g, ''));
这篇关于使用FileSaver和Blob将响应正文另存为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!