角6从API下载excel

时间:2019-04-10 19:32:27

标签: angular asp.net-web-api

我正在尝试从服务器下载Excel文件。 UI为角度6,服务为C#Web API。首先,我不知道此下载方法是否需要为HTTPGET或HTTPPOST。在其他论坛的帮助下,我在下面编写了代码。我没有看到任何错误,也没有看到调试器停止在subscription方法内。当我单击文件链接以从angular应用程序下载时,页面重定向到localhost:端口(起始页面)

     [HttpGet]//http get as it return file 
        public HttpResponseMessage DownloadAttachment(string fileName)
        {
            //below code locate physical file on server 
            var localFilePath = HttpContext.Current.Server.MapPath("../../uploadFiles/" + fileName);
            HttpResponseMessage response = null;
            if (!File.Exists(localFilePath))
            {
                //if file not found than return response as resource not present 
                response = Request.CreateResponse(HttpStatusCode.Gone);
            }
            else
            {
                //if file present than read file 
                var fStream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read);

               //compose response and include file as content in it
                response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    // Content = new StreamContent(fStream)
                    Content = new StreamContent(fStream)
                };

                //set content header of reponse as file attached in reponse
                response.Content.Headers.ContentDisposition =
                new ContentDispositionHeaderValue("attachment")
                {
                    FileName = Path.GetFileName(fStream.Name)
                };
                //set the content header content type as application/octet-stream as it      
                //returning file as reponse 
               response.Content.Headers.ContentType = new
                             MediaTypeHeaderValue("application/octet-stream");


                response.Content.Headers.ContentLength = fStream.Length;
                response.Headers.Add("fileName", fileName);
            }
            return response;
        }

现在,来自Angular调用:

   downloadFile(fileName: string) {
  this.Service.postAndGetResponse(fileName).subscribe(fileData => {
   // const b: any = new Blob([fileData], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    // .map(res => new Blob([res.blob()],{ type: 'application/vnd.ms-excel' }));
   // const  url = window.URL.createObjectURL(b);
   //   window.open(url);
   console.log (fileData);
    }
  );
}

在Service.ts

     postAndGetResponse(fileName) {
    return this.http.get(this.baseURL + 'DataEvent/DownloadEventAttachment?fileName=' + fileName, {responseType: 'blob' as 'blob'}).pipe(
      map((x) => {
        return x;
    })
    );
  }

我已将调试器放置在订阅中的downloadFile方法中,但它从未停止过,就好像什么都没有返回或调用丢失一样。

当我使用邮递员调用WEB API方法时,将返回响应。我没有看到任何文本格式-似乎已损坏/二进制?响应正文中的格式如下:

    ��ࡱ�>��   �����������������

2 个答案:

答案 0 :(得分:0)

我试图复制您的代码。以下代码有效。更改postAndGetResponse中的代码只会返回http get调用。

您可以使用链接或FileSaver保存Blob内容。

postAndGetResponse(fileName) {
    return this.http.get('http://localhost:62292' + '/api/TestExport/DownloadAttachment?fileName=' + fileName, { responseType: 'blob' as 'blob' });
  }

更新下载文件方法

downloadFile(fileName: string) {
    this.settingService.postAndGetResponse(fileName).subscribe(fileData => {

      const blob: any = new Blob([fileData], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

      let link = document.createElement("a");

      if (link.download !== undefined) {
        let url = URL.createObjectURL(blob);
        link.setAttribute("href", url);
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }
    );
  }

和API代码,将动词更改为[AcceptVerbs("GET")]

public class TestExportController : ApiController
    {

        [Route("api/TestExport/DownloadAttachment")]
        [AcceptVerbs("GET")]
        public HttpResponseMessage DownloadAttachment(string fileName)
        {
            //below code locate physical file on server 
            var localFilePath = HttpContext.Current.Server.MapPath("../../uploadFiles/" + fileName);
            HttpResponseMessage response = null;
            if (!File.Exists(localFilePath))
            {
                //if file not found than return response as resource not present 
                response = Request.CreateResponse(HttpStatusCode.Gone);
            }
            else
            {
                //if file present than read file 
                var fStream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read);

                //compose response and include file as content in it
                response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    // Content = new StreamContent(fStream)
                    Content = new StreamContent(fStream)
                };

                //set content header of reponse as file attached in reponse
                response.Content.Headers.ContentDisposition =
                new ContentDispositionHeaderValue("attachment")
                {
                    FileName = Path.GetFileName(fStream.Name)
                };
                //set the content header content type as application/octet-stream as it      
                //returning file as reponse 
                response.Content.Headers.ContentType = new
                              MediaTypeHeaderValue("application/octet-stream");


                response.Content.Headers.ContentLength = fStream.Length;
                response.Headers.Add("fileName", fileName);
            }
            return response;
        }
    }

答案 1 :(得分:0)

我发现发给某人的帖子需要遇到相同问题的帮助:

    downloadFile(fileName: string) {
   const isIE = /*@cc_on!@*/false || !!document['documentMode'];
   const isChrome = !!window['chrome'];
    this.service.postAndGetResponse(fileName).subscribe(fileData => {
    const blob: any = new Blob([fileData], { type: 'application/vnd.openxmlformats- 
      officedocument.spreadsheetml.sheet' });
    if (isIE) { // this code doesn't work for chrome
      console.log('Manage IE download>10');
      window.navigator.msSaveOrOpenBlob(blob, fileName);
  } else if (isChrome) {  // this below code doesn't work for IE
    const link = document.createElement('a');
    if (link.download !== undefined) {
     const url = URL.createObjectURL(blob);
     link.setAttribute('href', url);
     link.setAttribute('download', fileName);
     link.setAttribute('target', '_self');
     document.body.appendChild(link);
     link.click();
     document.body.removeChild(link);
    }
  } else {
    window.navigator.msSaveOrOpenBlob(blob, fileName);
  }
});
}