简体   繁体   中英

ASP.NET Web API return excel file to client

I have C# api code as below. It work correct when i run on visual studio and deploy to iis server. I consume this api by javascript or Angualar on production Front end. It work smooth if byte[] small size.

    [HttpPost]
    [Route("TestDownload2")]
    public HttpResponseMessage TestDownload2()
    {
        UTF8Encoding utf8 = new UTF8Encoding();
        byte[] data = new byte[Convert.ToInt32(ConfigurationManager.AppSettings["byteLength"].ToString())];
        ByteArrayContent byteContent = new ByteArrayContent(data);
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Access-Control-Allow-Origin", "*");
        response.Content = byteContent;
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = ConfigurationManager.AppSettings["byteLength"].ToString() + "Schedule Report.xlsx"
        };
        HttpConfiguration config = GlobalConfiguration.Configuration;

        return response;
    }

This application will occur error if byte[] have large size such as 2500. In browser's console appear.net::ERR_CONNECTION_RESET 200 (OK). I try other way to return other type and setting IIS but it doesn't work.

As I understand,

You will need to set settings inside web.config

<configuration>
    <system.web>
        <!-- This will handle requests up to 5GB -->
        <httpRuntime maxRequestLength="5242880" timeout="3600" />
    </system.web>
</configuration>

Or else you can download in memory of browser using reportProgress and once all steam data downloaded you can ask user directly via enable button to download instantly

const req = new HttpRequest('POST', '/download/file', file, {
  reportProgress: true,
  observe: 'events'
});

I hope it will help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM