Download a string as a file

2019-07-26 01:12发布

When the user clicks a button, I want to build a string, then have the user download that string as a file (it's a CSV file).

    var response = HttpContext.Current.Response;
    response.ClearContent();
    response.Clear();
    byte[] bytes = Encoding.ASCII.GetBytes(csvtext);
    using (var stream = new MemoryStream(bytes))
    {
        response.AddHeader("Content-Disposition", "attachment; filename=somefile.csv");
        response.AddHeader("Content-Length", stream.Length.ToString());
        response.ContentType = "text/plain";
        stream.WriteTo(response.OutputStream);
    }

This is what I have so far, and I have a feeling I'm pretty close, but I get the following error message:

Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. Details: Error parsing near '[The first bit of the CSV file]'.

I'm at a loss, and a deadline is fast approaching. Any help is greatly appreciated.

4条回答
乱世女痞
2楼-- · 2019-07-26 01:25

This may answer your question. Specifically you should use "text/csv" as content type.

查看更多
贪生不怕死
3楼-- · 2019-07-26 01:39

You can't do this with a partial/async postback with Ajax. You'll need to make whatever button you have triggering this download a PostBackTrigger for your UpdatePanel. Details here: http://www.asp.net/Ajax/Documentation/Live/mref/T_System_Web_UI_PostBackTrigger.aspx

查看更多
等我变得足够好
4楼-- · 2019-07-26 01:42

I would let the button post to an .ashx-handler (here's a tutorial on those) and put the code you have written in your post (with some small changes perhaps) in the ProcessRequest method in the handler.

Edit: Also, you might be interested in this question.

查看更多
贼婆χ
5楼-- · 2019-07-26 01:45

My guess is that you are in an AJAX Update Panel. If you are doing this type of action it must be done via a postback.

查看更多
登录 后发表回答