Returning a downloadable file using a stream in as

2020-02-28 05:51发布

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

 Stream strm1 = GenerateReport(Id);

return File(strm1, 
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "Report_" + reportId.ToString() + ".xlsx");

Notice how I am passing strm1 which is a stream. I can then name it Report_+ ...xlsx like the example above shows.

Is there a similar way to do this with asp.net web forms using c#.

标签: asp.net
3条回答
Fickle 薄情
2楼-- · 2020-02-28 05:56

Or if you have a stream ready to be written, simply copy it to response stream:

Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment; filename={your file name}");
Response.OutputStream.Write(stream, 0, stream.length);
Response.End();

Added same code just for visibility

查看更多
够拽才男人
3楼-- · 2020-02-28 06:12

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);
}
查看更多
不美不萌又怎样
4楼-- · 2020-02-28 06:17

I use this extension to send a stream as a downloadable file:

public static class ToDownloadExtention
{
   public static void ToDownload(this Stream stream, string fileName, HttpResponse response)
    {
        response.Clear();
        response.ContentType = "application/octet-stream";
        response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
        stream.CopyTo(response.OutputStream);
        response.End();
    }
}

And the usage is:

var stream = new MemoryStream();

stream.ToDownload("someFileName.ext",Response);
查看更多
登录 后发表回答