user3537250 February 2016

Response.end doesn't work

I try to download a .xlsx documnent using Response.End() and OpenXml. But nothing happens. It's stuck in 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
}

The same problem appears when I try use Response.Flush(). If I use CompleteRequest() instead Response.End() .xlsx file is empty

Answers


Timothy Dooling March 2016

This works for me for all files:

    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();
    }

The FileContentResult is a result of using the File method of the Controller class in MVC.

I also believe what you are missing is closing the workbook before trying to output it.

I would suggest adding spreadsheetDocument.Close() followed by memoryStream.Flush() to your code before trying to output it to the view.

The contentDisposition is simply String.Format("attachment;filename={0}", fileName).

Also, Response.End() throws an error, so always use the other one.

Post Status

Asked in February 2016
Viewed 2,582 times
Voted 4
Answered 1 times

Search




Leave an answer