从后端获取 zip 文件

问题描述

我正在尝试在后端生成文件,然后返回一个包含所有这些文件的 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,...,19,109,121,17,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');
});

解决方法

我认为下载 zip 文件的一个更简单的解决方案是在后端创建文件并将路径(作为链接)发送到前端,并且只需要一个带有链接的 href 以便浏览器启动下载

>