通过Ajax调用通过Web方法从C#下载文件?

时间:2012-08-23 07:47:25

标签: ajax webmethod

我试图通过webmethod从服务器下载文件 但它对我不起作用。 我的代码如下

     [System.Web.Services.WebMethod()]
public static string GetServerDateTime(string msg)
{
    String result = "Result : " + DateTime.Now.ToString() + " - From Server";
    System.IO.FileInfo file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["FolderPath"].ToString()) + "\\" + "Default.aspx");
    System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
    Response.ClearContent();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
    Response.AddHeader("Content-Length", file.Length.ToString());
    Response.ContentType = "application/octet-stream";
    Response.WriteFile(file.FullName);
    //HttpContext.Current.ApplicationInstance.CompleteRequest();
    Response.Flush();
    Response.End();
    return result;        
}

我的ajax调用代码如下

    <script type="text/javascript">
    function GetDateTime() {
                    var params = "{'msg':'From Client'}";
                    $.ajax
                      ({
                          type: "POST",
                          url: "Default.aspx/GetServerDateTime",
                          data: params,
                          contentType: "application/json;charset=utf-8",
                          dataType: "json",
                          success: function (result) {
                              alert(result.d);
                          },
                          error: function (err) {

                          }
                      });
    }
</script>

我在按钮点击中调用了这个功能..

我不知道如何使用其他方法下载文件

如果有其他可用的方法,请建议我,或者使用相同的代码进行更正。

感谢所有..

3 个答案:

答案 0 :(得分:10)

WebMethod无法控制当前的响应流,因此无法以这种方式执行此操作。当你从javascript调用web方法时,响应流已经传递给客户端了,你无能为力。

执行此操作的选项是WebMethod将文件生成为服务器上某处的物理文件,然后将生成的文件的url返回给调用的javascript,后者又使用window.open(...)打开它。
除了生成物理文件,您可以调用一些GenerateFile.aspx来执行您最初在WebMethod中尝试的内容,但是在Page_Load中执行,并从javascript调用window.open('GenerateFile.aspx?msg=From Clent')

答案 1 :(得分:3)

不是调用Web方法,而是使用通用处理程序(.ashx文件)并将代码下载到处理程序的ProcessRequest方法中来下载文件。

答案 2 :(得分:2)

这是Ajax Call

             $(".Download").bind("click", function () 
             {
                var CommentId = $(this).attr("data-id");
                $.ajax({
                   type: "POST",
                   contentType: "application/json; charset=utf-8",
                   url: "TaskComment.aspx/DownloadDoc",
                   data: "{'id':'" + CommentId + "'}",
                   success: function (data) {


                   },
                   complete: function () {

                }
            });
        });

C#背后的代码

   [System.Web.Services.WebMethod]
   public static string DownloadDoc(string id)
   {
       string jsonStringList = "";
       try
       {
        int CommentId = Convert.ToInt32(id);
        TaskManagemtEntities contextDB = new TaskManagementEntities();
        var FileDetail = contextDB.tblFile.Where(x => x.CommentId == CommentId).FirstOrDefault();
        string fileName = FileDetail.FileName;
        System.IO.FileStream fs = null;
        string path = HostingEnvironment.ApplicationPhysicalPath + "/PostFiles/" + fileName;
        fs = System.IO.File.Open(path + fileName, System.IO.FileMode.Open);
        byte[] btFile = new byte[fs.Length];
        fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
        fs.Close();
        HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=" + fileName);
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.BinaryWrite(btFile);
        HttpContext.Current.Response.End();
        fs = null;
        //jsonStringList = new JavaScriptSerializer().Serialize(PendingTasks);
    }
    catch (Exception ex)
    {

    }
    return jsonStringList;
}