ASP.NET从内存中流内容,而不是从文件中流

时间:2009-06-03 20:07:41

标签: asp.net dynamic download stream

用户已请求“下载”GridView内容的csv文件表示的选项。有没有人知道如何在不将文件保存到服务器的情况下这样做,而只是从内存中将其传输给用户?

由于

4 个答案:

答案 0 :(得分:2)

实施IHttpHandler。

我在ProcessResponse中使用类似于以下的内容来输出以前在数据库表中构建的CSV ...

public void ProcessRequest(HttpContext context)
{
    HttpResponse response = context.Response;
    HttpRequest request = context.Request;

    //Get data to output here...

    //Turn off Caching and enforce a content type that will prompt to download/save.
    response.AddHeader("Connection", "close");
    response.AddHeader("Cache-Control", "private");
    response.ContentType = "application/octect-stream";

    //Give the browser a hint at the name of the file.
    response.AddHeader("content-disposition", string.Format("attachment; filename={0}", _filename));

    //Output the CSV here...
    foreach(BatchDTO.BatchRecordsRow row in dtoBatch.BatchRecords)
        response.Output.WriteLine(row.Data);

    response.Flush();
    response.Close();
}

有许多库可以让生成CSV变得更容易,你应该只能将它传递给Response.OutputStream,让它写入那里而不是文件流。

答案 1 :(得分:1)

使用context.Response.OutputStream。

Here's一个例子。

答案 2 :(得分:1)

我创建了一个StringBuilder并使用以下代码将内容转储到Response对象(“csv”是StringBuilder变量)。

    Response.ContentType = @"application/x-msdownload";
    Response.AppendHeader("content-disposition", "attachment; filename=" + FILE_NAME);

    Response.Write(csv.ToString());
    Response.Flush();
    Response.End();

答案 3 :(得分:0)

我已经使用了RKLib导出库几次效果很好,这使用了一个内存流,可以给出任何数据表,它将导出为csv下载:

http://www.codeproject.com/KB/aspnet/ExportClassLibrary.aspx

相关问题