简体   繁体   English

ASP.NET Web API 返回 excel 文件给客户端

[英]ASP.NET Web API return excel file to client

I have C# api code as below.我有 C# api 代码如下。 It work correct when i run on visual studio and deploy to iis server.当我在 visual studio 上运行并部署到 iis 服务器时,它工作正常。 I consume this api by javascript or Angualar on production Front end.我在生产前端通过 javascript 或 Angualar 使用这个 api。 It work smooth if byte[] small size.如果 byte[] 小,它工作顺利。

    [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).如果 byte[] 的大小很大,例如 2500,此应用程序将发生错误。在浏览器的控制台中出现 .net::ERR_CONNECTION_RESET 200 (OK)。 I try other way to return other type and setting IIS but it doesn't work.我尝试其他方式返回其他类型并设置 IIS 但它不起作用。

As I understand,我认为,

You will need to set settings inside web.config您需要在 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或者您可以使用 reportProgress 在浏览器的 memory 下载,一旦所有 Steam 数据下载完毕,您可以通过启用按钮直接询问用户是否立即下载

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

I hope it will help我希望它会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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