【发布时间】:2021-10-10 20:57:26
【问题描述】:
我正在尝试在后端生成文件,然后返回一个包含所有这些文件的 zip 文件。
后端函数如下所示:
import { saveAs } from 'file-saver';
@Get('encrypt/all')
async encryptAllRecipes() {
const zip: JSZip = new JSZip();
const allRecipes: RecipeEntity[] = await this.listAllRecipes();
for(const recipe of allRecipes) {
const encryptedRecipeStr: string = await this.encryptRecipe(recipe);
zip.file(`${recipe.name}.enc`, encryptedRecipeStr);
}
const buffer: Buffer = await (zip.generateAsync({type:"nodebuffer"}, function updateCallback(metadata) {
console.log("progression: " + metadata.percent.toFixed(2) + " %");
}));
return buffer;
}
这个函数的答案看起来是这样的(我在里面用“...”截断了它,因为它太大了)
{"type":"Buffer","data":[80,75,3,4,...,0,0,0,19,0,109,4,0,0,121,17,0,0,0,0]}
然后,在前端,我想下载 zip 文件:
exportAllToEncryptedFile() {
const headers = new HttpHeaders();
const params: HttpParams = new HttpParams();
return this._httpRequestsManager
.get(`${this._constants.encryptAllRecipesAddress}`, {headers, params, responseType: 'arraybuffer'})
.subscribe((response: any) => {
const blob = new Blob([response], { type: 'arraybuffer' });
saveAs(blob, `encryptedRecipes.zip`);
},
(err: HttpErrorResponse) => {
console.log(err);
}
);
}
该文件无法以 zip 格式读取,它包含后端返回的 json。我尝试了很多东西,其中:
- 从后端使用 base64 编码返回缓冲区,并从前端解码此字符串
- 将“responseType”与“blob”和“arraybuffer”一起使用
- 将 response.data 字段存储在文件中,而不是整个响应
- 将标头的内容类型定义为“application/zip”、“text/plain”、“multipart/form-data”
我对 http 查询不是很有经验。我该怎么办?
谢谢。
编辑:从后端,如果我直接将缓冲区写入文件,则生成的文件是正确的。
fs.writeFile('C:\\ziptests\\testBlob.zip', buffer, () => {
console.log('file written');
});
【问题讨论】: