【问题标题】:Read file and its properties from API and download it in Angular Client从 API 读取文件及其属性并在 Angular 客户端中下载
【发布时间】:2021-04-12 01:33:27
【问题描述】:

需要根据类型下载客户端api返回的动态文件。这就是我所拥有的

我的api控制器看起来像这样

    public async Task<IActionResult> GetFile(int id)
    {

         IBaseResult<UserDetails> result = await _Bo.GetUSerDetails(id);
         
         //result will have content likes 

         //1. FileName//fileaname.{extention}
         //2. FileType//eg.application/pdf or application/doc
         //3. FileContent//byte[]

         if (result.Data != null)
         {
             response.Success = result.success;
             response.Data = result.Data;

             return Ok(response);
         }
     }

.ts 文件如下所示

  data.service.ts

  getResume(methodName: string, id :string): Observable<any> {
       let httpOptions = this.getAuthoriseHeader();
       return this.http.get(environment.baseApiUrl + methodName + id, { headers: httpOptions, observe: 'response', responseType: 'blob' });

   }

  view.component.ts

     this.dataservice.getResume(method, id).subscribe(result => {
         var resume = result["data"];
         var fileName = resume.resumeName;
         var fileType = resume.resumeType;

         const file = new Blob([resume.resume], { type: fileType  });//Is this correct or do i need to use 'application/octet-stream' here?

         saveAs(file, fileName);
     });

上面的实现文件正在下载,但是当我尝试打开文件时,显示如下g

而我的响应对象是

更新:

我在我的 .ts 文件中试过这个

var fileName = resume.resumeName; var fileType = resume.resumeType; //var byteArray = new Uint8Array(resume.resume);

      const file = new Blob([resume.resume], { type: 'application/octet-stream' });

      this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(file));

      let a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display: none');
      a.href = this.fileUrl;
      a.download = fileName;
      a.click();
      window.URL.revokeObjectURL(this.fileUrl);
      a.remove();

文件正在下载,出现失败 - 无文件错误

【问题讨论】:

    标签: angular typescript blob filecontentresult


    【解决方案1】:

    这是我下载文件的方法(在我的例子中是 Excel,但我认为这没有什么不同,因为我们都使用 Blob)。我已经安装了ngx-filesaver 并将其用作依赖注入。

    import { FileSaverService } from 'ngx-filesaver';
    
    constructor(
      private http: HttpClient,
      private fileSaver: FileSaverService
    ) {}
    
    export(): Observable<any> {
      const body = {...};
      return this.http.post(`${environment.api}/export`, body, {
          responseType: 'blob',
          observe: 'response',
        });
    }
    
    anotherFunction() {
      this.export().subscribe(({ body, headers }: HttpResponse<any>) => {
        const blob = new Blob([body], { type: headers.get('content-type') });
        this.fileSaverService.save(blob, 'your_file_name.xlsx');
      });
    }
    

    编辑

    这是console.log(body, headers)的画面

    【讨论】:

    • 嗨,您的 api 控制器中的 Emilien,您如何返回文档详细信息?你能分享它的快照吗?您还在控制器中使用内容处置吗?
    • 在提出请求时不要忘记使用responseType: 'blob', observe: 'response',。我添加了我得到的截图。我没有使用内容处置。
    • 我在我的实施中有,但是为了起草这个问题我添加了选定的项目,我会更新问题
    • 我设法找到了解决方案 Emilien,现在它正在工作,请参阅我发布的答案。谢谢你的帮助....
    【解决方案2】:

    最后我找到了解决方案,现在它工作正常。我怀疑这是将我的 blob 数据转换为保存的问题。

     const binaryString = window.atob(resume.resume); // Comment this if not using base64
     const bytes = new Uint8Array(binaryString.length);
     return bytes.map((byte, i) => binaryString.charCodeAt(i));
    

    然后我用了

    const blob = new Blob([body]);
    //rest of the code is same as posted question
    

    这篇文章对解决方案很有帮助

    https://medium.com/@riccardopolacci/download-file-in-javascript-from-bytea-6a0c5bb3bbdb

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-21
      • 2016-10-28
      • 2023-04-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多