ASP.NET stream content from memory and not from file

前端 未结 4 529
失恋的感觉
失恋的感觉 2020-12-18 16:15

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 bu

4条回答
  •  长情又很酷
    2020-12-18 16:32

    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.

提交回复
热议问题