Angular不会使用FileSaver从字节数组保存文件

时间:2019-04-10 10:34:47

标签: angular asp.net-web-api angular5

我的Web api中有一个服务,该服务以字节数组的形式返回文件:

[HttpPost]
[Route("api/downloadFiles")]
public HttpResponseMessage DownloadFile([FromBody] string filePath)
{
    try
    {
        MemoryStream fileContent = new MemoryStream();
        if (File.Exists(filePath))
        {
            HttpResponseMessage response = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content = new ByteArrayContent(File.ReadAllBytes(filePath))
            };
            response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = Path.GetFileName(filePath);
            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
            response.Content.Headers.ContentLength = new FileInfo(filePath).Length;
            return response;
        }
        else
            return Request.CreateResponse(HttpStatusCode.NotFound);
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "The server failed to retrieve the file");
    }
}

然后我在中间人服务中捕获内容,并将其作为字节数组传递给前端:

fileFromServer = await response.Content.ReadAsByteArrayAsync();
return fileFromServer;

到目前为止,一切似乎都正常。我得到一个字节数组并将其返回到前端。

接下来,我有一个服务和组件代码,应将其保存为文件:

 downloadFile(filename: string): Observable<Blob>{
   let headers = new Headers();
    headers.append('Content-Type', 'application/json; charset=utf-8');
    return this._http.post((this.baseUrl_GatewaySvc + 'downloadFiles'), JSON.stringify(filename), { headers: headers }).map(res => res.blob());
 }

以及组件:

import { saveAs as importedSaveAs } from 'file-saver';

 onDownloadFileClick(index: number): void {
    this._GatewaySvc.downloadFile('server-share-path' + this.Files[index].FileName).subscribe(
    fileFromServer => {
      $('#errorMsgModal').modal('show');
      $('#errMsgOnModal').text(fileFromServer);      
      var fileName = this.Files[index].FileName;
      importedSaveAs(fileFromServer, fileName);
      },
      error => { 
      $('#errorMsgModal').modal('show');
      $('#errMsgOnModal').text('Download finished' + error.status + ' ' + error.statusText); },
      () => {
        $('#errorMsgModal').modal('show');
        $('#errMsgOnModal').text('Download finished');
      }
    );
  }

这进入error部分,显示以下文本:

  

下载完成的未定义未定义

如何正确保存文件?

0 个答案:

没有答案