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

标签 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>

我已经在按钮单击中调用了此功能。

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

如果有其他可用方法,请给我建议,或在同一代码中给出更正。

谢谢大家..

最佳答案

WebMethod无法控制当前响应流,因此无法通过这种方式进行控制。当您从javascript调用Web方法时,响应流已经传递到客户端,您对此无能为力。

一种选择是,WebMethod在服务器上某个位置将文件作为物理文件生成,然后将生成文件的URL返回给调用JavaScript,后者再使用window.open(...)将其打开。
代替生成物理文件,您可以调用一些GenerateFile.aspx来完成您最初在WebMethod中尝试的操作,但是可以使用Page_Load进行操作,然后从javascript调用window.open('GenerateFile.aspx?msg=From Clent')

关于ajax - 通过Ajax调用通过Web方法从C#下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12086999/

相关文章:

javascript - 如何调用母版页的web方法?

ASP.NET 单声道 : How to send SOAP instead of HTML?

c# web 服务不返回结果

java - 如何用servlet + ajax制作动态内容

javascript - 实时表编辑其他 mySQL 表中的显示字段

javascript - 将 Javascript 对象传递给 PHP JSON 解码

javascript - 在弹出窗口中打开部分 View

jquery - 将 html 元素的 id 传递给 php

javascript - 为什么我们使用 web 服务的 web 方法,而不是 web 表单函数