下载一个字符串当作文件 [英] Download a string as a file

查看:162
本文介绍了下载一个字符串当作文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户点击一个按钮,我想建立一个字符串,然后让用户下载该字符串作为文件(这是一个CSV文件)。

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

这是我到目前为止,我有一种感觉,我是pretty接近,但我得到了以下错误消息:

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

微软JScript运行时错误:Sys.WebForms.PageRequestManagerParserErrorException:从服务器收到的消息无法解析。此错误的常见的原因是当响应由呼叫修改为回复于(),响应滤波器,的HttpModules或服务器跟踪被使能。
详细信息:错误解析附近[CSV文件的第一位]

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]'.

我在一个损失,而截止日期已经临近。任何帮助是极大的AP preciated。

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

推荐答案

您不能使用Ajax部分/异步回发做到这一点。你需要做出力所能及的按钮,您可以触发此下载一个PostBackTrigger为您的UpdatePanel。详情点击这里:的http://www.asp.net/Ajax/Documentation/Live/mref/T_System_Web_UI_PostBackTrigger.aspx

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

这篇关于下载一个字符串当作文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆