Returning a downloadable file using a stream in asp.net web forms

后端 未结 3 775
旧巷少年郎
旧巷少年郎 2020-12-10 05:20

In asp.net MVC I can do something like the following which will open a stream:

 Stream strm1 = GenerateReport(Id);

return File(strm1, 
            \"applica         


        
3条回答
  •  萌比男神i
    2020-12-10 05:29

    You can use TransmitFile or WriteFile if the file is in your website folder.

    string fileName = string.Format("Report_{0}.xlsx", reportId);
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("Content-Disposition", 
       string.Format("attachment; filename={0}", fileName));
    Response.TransmitFile(fileName);
    Response.End();
    

    Stream

    If your data is already in Memory, you want this method which writes the response in chunks.

    Stream stm1 = GenerateReport(Id);
    Int16 bufferSize = 1024;
    byte[] buffer = new byte[bufferSize + 1];
    
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("Content-Disposition", 
        string.Format("attachment; filename=\"Report_{0}.xlsx\";", reportId));
    Response.BufferOutput = false;
    int count = stm1.Read(buffer, 0, bufferSize);
    
    while (count > 0)
    {
        Response.OutputStream.Write(buffer, 0, count);
        count = stm1.Read(buffer, 0, bufferSize);
    }
    

提交回复
热议问题