我试图通过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; }
<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方法时,响应流已经传递给客户端,并且您无法对其进行任何操作.
原文链接:https://www.f2er.com/ajax/159890.html执行此操作的选项是WebMethod将文件生成为服务器上某处的物理文件,然后将生成的文件的url返回给调用的javascript,后者又使用window.open(…)打开它.除了生成一个物理文件,您可以调用一些GenerateFile.aspx来完成您最初在WebMethod中尝试的内容,但是在Page_Load中执行,并调用window.open(‘GenerateFile.aspx?msg = From Clent’) JavaScript的.