通过HTTP处理程序下载csv文件



尝试下载csv文件时,我在使用HttpContext.Current.Response.End();时出错。我搜索错误并获得解决方案.使用处理程序以避免Response.End();

我的处理程序 :

public class DownloadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string table = HttpContext.Current.Request.QueryString["table"].ToString();
        string fileName = HttpContext.Current.Request.QueryString["fileName"].ToString();
        table = table.Replace(">", ">");
        table = table.Replace("&lt;", "<");
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName + "_" + DateTime.Now.ToString("M_dd_yyyy_H_M_s") + ".csv");
        HttpContext.Current.Response.ContentType = "application/text";
        HttpContext.Current.Response.Write(table);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

我在按钮单击中调用此处理程序,如下所示。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Mypath/DownloadHandler.ashx?table=" + csv + "&fileName=User-Report");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

它调用处理程序。我没有错误,但csv文件没有下载?我无法弄清楚哪里是一个真正的问题。我可以在代码中遗漏某些内容吗?感谢您的帮助。

注意:csv是一个字符串,来自另一个不是真正问题的进程。

如果你正在做 HttpWebRequest,那么你必须请求然后 getResponse。从响应流中读取并保存。

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:57169/DownloadHandler.ashx?table=tttex&fileName=User-Report");
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        byte[] data = new System.IO.BinaryReader(response.GetResponseStream()).ReadBytes((int)response.ContentLength);
        System.IO.File.WriteAllBytes("C:\Temp.csv", data);

如果您想下载浏览器,那么只需执行以下操作即可。

  Response.Redirect("http://yourpath/DownloadHandler.ashx?table=tttex&fileName=User-Report");

最新更新