Save a response body as file with FileSaver and blob

杀马特。学长 韩版系。学妹 提交于 2019-12-11 01:49:46

问题


I want to download and save a file from an api. The name of my file is text.txt but the saved file is called: _text.txt_ and the content of this file is: [object Object]

This is my function to download as file:

const options = {
      headers: new HttpHeaders().append('Authorization', this.oAuthService.getAccessToken()),
      params: new HttpParams().append('responseType', 'text'),
      observe: 'response' as 'response'
    }

    return this.http.get(this.fileServerUrl + 'file/download/' + filename + '/' + version, options)
      .subscribe(
        resp => { this.saveToFileSystem(resp)

      });
  }

  private saveToFileSystem(response) {
    const contentDispositionHeader: string = response.headers.get('Disposition');
    const parts: string[] = contentDispositionHeader.split(';');
    const filename = parts[1].split('=')[1];
    filename.replace(/"/g, '');
    console.log(filename);
    console.log(response.body)
    const blob = new Blob([response.body], { type: 'text/plain' });
    saveAs(blob, filename);
  }

the output of the first console.log is text.txt and the console.log of the response.body is: this is a test text..

so why is the saved file name with _ at the begin and end and the content not the text from the response body.

Thanks in advnace


回答1:


Try this:

const blob = new Blob([JSON.stringify(response.body)], { type: 'text/plain' });

And for _text.txt_: String is immutable type. So filename.replace... will not change filename value, it's returns new value. You have to create new variable:

const newFileName = filename.replace(/"/g, '');
...
saveAs(blob, newFileName);

or just put filename.replace(/"/g, '') into saveAs

saveAs(blob, filename.replace(/"/g, ''));


来源:https://stackoverflow.com/questions/52078312/save-a-response-body-as-file-with-filesaver-and-blob

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!