首页 > 解决方案 > 从 byte[] 下载 PDF

问题描述

服务器端(Visual Studio 2015)

我有一个 pdf 存储在我的服务器端。当通过 WebApi 从客户端调用时,我使用以下指令读取内容并将其存储在变量中:

byte[] bytes = File.ReadAllBytes(path);

然后我使用以下指令将文件内容发送给客户端:

return Request.CreateResponse(HttpStatusCode.OK, bytes);

客户端(Angular 7) 安装了 FileSaver,我收到文件内容,它看起来像这样

JVBERi0xLjUNCiW1tbW1DQoxIDAgb2Jq...eXBlL0NhdGFsb2cvUG

然后我尝试通过以下方式下载它:

this.fileService.fileDownload().subscribe(bytes => {
    const file = new Blob([bytes], {type: 'application/pdf'});
    saveAs(file, 'file.pdf');
}

使用 fileService 中的以下方法调用服务器 API:

fileDownload(id): Observable<HttpResponse<any>>{
    const httpOptions = {
      'responseType'  : 'arraybuffer' as 'json'
    };
    return this.http.get<any>('http://localhost:55820/api/files/12',httpOptions);
  }

但该文件已损坏或 Acrobat Reader 不承认该文件。

我还希望它适用于其他文件类型,文件内容位于byte[]、内容类型定义(文本/纯文本、应用程序/pdf)和带有扩展名的文件名。我怎样才能标准化这个过程?

标签: arrays.netangularfile

解决方案


httpOptions应该是{ responseType: 'blob' }

试试这样:

fileDownload(id): Observable<HttpResponse<any>>{
    return this.http.get('http://localhost:55820/api/files/12',{ responseType: 'blob' });
}



this.fileService.fileDownload().subscribe(bytes => {
    saveAs(file, 'file.pdf');
}

推荐阅读