角6从API下载excel [英] angular 6 download excel from API

查看:54
本文介绍了角6从API下载excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to download an excel file from server. UI is in angular 6 and service is C# Web API. Firstly, I am not getting whether this download method need to be HTTPGET or HTTPPOST. Using some help from other forum, I have written code below. I don't see any error nor I see that debugger stop inside subscribe method. when I click on file link to download from angular app the page redirect to localhost: port (start page)

     [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调用:

Now, from Angular calling:

   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

in Service.ts

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

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

I have put debugger in downloadFile method inside subscribe, but it never stops there as if nothing is returned or call is lost.

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

When I use postman to call WEB API method, the response is returned. I don't see any text format- it seems to be corrupted/binary?? the format is like below in response body:

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

推荐答案

我试图重现您的代码.以下代码有效.更改postAndGetResponse中的代码只会返回http get调用.

I tried to reproducing your code. Following code is worked. Change code in postAndGetResponse only return http get call.

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

You can use link or FileSaver to save blob content.

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")]

And API code, change verb to [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;
        }
    }

这篇关于角6从API下载excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆