Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

dynamic - ASP.NET stream content from memory and not from file

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...