簡體   English   中英

Response.end不起作用

[英]Response.end doesn't work

我嘗試使用Response.End()和OpenXml下載.xlsx文檔。 但是什么也沒發生。 它卡在Response.End()

public void DownloadStudents(int InstituteId, int DepartmentId)
{ 
     var memoryStream = new MemoryStream();

     using (var spreadsheetDocument = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook))
     {
         //Some code
         foreach (var line in users)
         {
              // Fill
         }

         spreadsheetDocument.WorkbookPart.Workbook.Save(); 
    } 

    var excelName = "Title.xlsx";

    Response.Clear();
    Response.CacheControl = "Private"; 
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("Content-Type", "application/octet-stream");
    Response.AppendHeader("content-disposition",string.Format("attachment; filename={0}; size={1}", excelName, memoryStream.Length));
    Response.BinaryWrite(memoryStream.ToArray());

    **//Problem is here.**  
    Response.End(); // In this line nothing happens
}

當我嘗試使用Response.Flush()時,也會出現相同的問題。 如果我使用CompleteRequest()代替Response.End() xlsx文件為空

這對我適用於所有文件:

    public static void outputFile(FileContentResult file, String contentDisposition)
    {
        var context = System.Web.HttpContext.Current;
        file.FileDownloadName = contentDisposition;
        context.Response.Clear();
        context.Response.ClearContent();
        context.Response.ClearHeaders();
        context.Response.AppendHeader("content-disposition", contentDisposition);
        context.Response.ContentEncoding = System.Text.Encoding.UTF8;
        context.Response.ContentType = file.ContentType;
        context.Response.AppendHeader("content-length", file.FileContents.Length.ToString());
        context.Response.BinaryWrite(buffer: file.FileContents.ToArray());
        context.Response.Flush();
        context.ApplicationInstance.CompleteRequest();
    }

FileContentResult是在MVC中使用Controller類的File方法的結果。

我還相信您所缺少的是在嘗試輸出工作簿之前將其關閉。

我建議在嘗試將其輸出到視圖之前,先將電子表格Document.Close()后跟memoryStream.Flush()添加到您的代碼中。

contentDisposition只是String.Format(“ attachment; filename = {0}”,fileName)。

另外,Response.End()會引發錯誤,因此請始終使用另一個錯誤。

暫無
暫無

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

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