通过Ajax调用通过Web方法从C#下载文件?
发布时间:2020-12-16 01:35:40 所属栏目:百科 来源:网络整理
导读:我试图通过webmethod从服务器下载文件 但它对我不起作用. 我的代码如下 [System.Web.Services.WebMethod()]public static string GetServerDateTime(string msg){ String result = "Result : " + DateTime.Now.ToString() + " - From Server"; System.IO.Fil
我试图通过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中执行,并调用window.open(‘GenerateFile.aspx?msg = From Clent’) JavaScript的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |