簡體   English   中英

ASP.NET Web API 返回 excel 文件給客戶端

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

我有 C# api 代碼如下。 當我在 visual studio 上運行並部署到 iis 服務器時,它工作正常。 我在生產前端通過 javascript 或 Angualar 使用這個 api。 如果 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;
    }

如果 byte[] 的大小很大,例如 2500,此應用程序將發生錯誤。在瀏覽器的控制台中出現 .net::ERR_CONNECTION_RESET 200 (OK)。 我嘗試其他方式返回其他類型並設置 IIS 但它不起作用。

我認為,

您需要在 web.config 中進行設置

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

或者您可以使用 reportProgress 在瀏覽器的 memory 下載,一旦所有 Steam 數據下載完畢,您可以通過啟用按鈕直接詢問用戶是否立即下載

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

我希望它會有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM