代码之家  ›  专栏  ›  技术社区  ›  tatsu

有没有一种方法可以不用fileaver或createObjectURL()将和API流保存为.csv

  •  0
  • tatsu  · 技术社区  · 6 年前

    这似乎是目前仅有的两种方法。

    createObjectURL()的问题是它已被弃用,我当前的浏览器chrome甚至不能再调用此方法。

    我在这里:

    const params = {'params' : p};
    const httpOptions = this.authenticationService.getRequestOptions();
    httpOptions['responseType'] = 'text/csv';
    
    this.http.post(
      this.url + this.currentId,
      params,
      httpOptions
    ).subscribe((response: any) => {
      console.log(response);
      const blob = new Blob([response], {type: 'text/csv'});
    
      const link = document.createElement('a');
      link.setAttribute('style', 'display: none');
      link.href = response; // should be a URI but document.URL.createObjectURL() is deprecated
      const date = new Date();
      link.download = 'file.csv';
      link.click();
      link.remove();
    }, error => {
      console.log('I failed :(', error);
    }); 
    

    这确实会触发文件的下载。但是我需要将blob转换成URI,我没有这个部分。

    编辑:

    为了清楚起见:

    截至2019年11月19日和2017年11月1日,window.URL.createObjectURL已弃用,将返回错误: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject

    更新:

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject

    https://code-examples.net/en/docs/dom/htmlmediaelement/srcobject

    Deprecation of createObjectURL and replace with the new HTMLMediaElement.srcObject doesn't work for Webcam stream

    它应该是 createObjectURL 但它只适用于视频元素

    1 回复  |  直到 6 年前
        1
  •  1
  •   tatsu    6 年前

    我通过一番挖掘和反复试验找到了解决办法。我想这将是一个惊喜,它可以如此容易地下载一个文件和那篇文章 createObjectURL()

    this.http.post(
      this.url + this.currentId,
      params,
      httpOptions
    ).subscribe((response: any) => {
      const link = document.createElement('a');
      link.setAttribute('style', 'display: none');
      link.href = 'data:attachment/csv,' + encodeURI(response); // <- it was as simple as this.
      const date = new Date();
      link.download = this.currentChoice + '-' + date.getDate() + '-' + (1 + date.getMonth()) + '-' + date.getFullYear() + '.csv';
      link.click();
      link.remove();
    }, error => {
      console.log('File download failed : ', error);
    });
    

    我的api的返回已经是我不需要调用的文件的原始内容 .text() 或者其他孩子。

    希望这有帮助:)