在Web服务器上强制下载文件 – ASP .NET C#

用户单击基于ASP.NET(C#)的Web应用程序中的按钮时,我需要强制下载.sql文件

当在按钮被点击时,保存为对话框应该在客户端打开…

我该如何做?

编辑

这是我正在使用的代码

string sql = "";
        using (System.IO.StreamReader rdr = System.IO.File.OpenText(fileName))
        {
            sql = rdr.ReadToEnd();
        }
        Response.ContentType = "text/plain";
        response.addheader("Content-disposition","attachment; filename=Backup.sql");
        Response.Write(sql);
        Response.End();

这是我正在收到的错误

alt text http://img40.imageshack.us/img40/2103/erroro.gif

怎么了?

解决方法

创建一个单独的HTTP处理程序(DownloadsqlFile.ashx):
<%@ WebHandler Language="C#" Class="DownloadHandler" %>

using System;
using System.Web;

public class DownloadHandler : IHttpHandler {
    public void ProcessRequest(HttpContext context) {
        var fileName = "myfile.sql";
        var r = context.Response;
        r.AddHeader("Content-disposition","attachment; filename=" + fileName);
        r.ContentType = "text/plain";
        r.WriteFile(context.Server.MapPath(fileName));
    }
    public bool IsReusable { get { return false; } }
}

然后使ASP.NET页面中的按钮导航到DownloadsqlFile.ashx。

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些