ASP.NET stream content from memory and not from fi

2019-01-26 01:35发布

The users have requested the option to "download" a csv file representation of GridView contents. Does anyone know how to do this without saving the file to the server but rather just streaming it to the user from memory?

Thanks

4条回答
做自己的国王
2楼-- · 2019-01-26 01:51

Use context.Response.OutputStream.

Here's an example.

查看更多
Lonely孤独者°
3楼-- · 2019-01-26 01:57

Implement an IHttpHandler.

I used something similar to the following in the ProcessResponse for outputing a CSV that had previously been constructed in a database table...

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

There are a number of libraries that make generating a CSV easier, you should just be able to pass it the Response.OutputStream to have it write to there rather than to a file stream.

查看更多
倾城 Initia
4楼-- · 2019-01-26 02:03

I created a StringBuilder and dump the contents to the Response object using the following code ("csv" is the StringBuilder variable).

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

    Response.Write(csv.ToString());
    Response.Flush();
    Response.End();
查看更多
Anthone
5楼-- · 2019-01-26 02:03

I have used the RKLib export library a few times to great effect, this uses a memory stream and can be given any datatable which it will export as a csv download:

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

查看更多
登录 后发表回答