Download C # file via web method via Ajax call?

I tried to download the file from the server via the web method but this does not work for me. my code is below

[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; } 

and my ajax call code is below

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

and I called this function at the click of a button.

I do not know how to upload a file using other methods

Please suggest me any other available methods or give me a fix in the same code.

Thanks to everyone ..

+4
source share
3 answers

WebMethod does not control the current response flow, so this cannot be done in this way. At the time you call the web method from javascript, the response flow is already being sent to the client, and you can do nothing about it.

The option for this is that WebMethod generates the file as a physical file somewhere on the server, and then returns the URL of the generated file to the calling javascript, which in turn uses window.open(...) to open it . <br> Instead of creating a physical file, you can call some GenerateFile.aspx, which does what you originally tried to use in your WebMethod, but do it in Page_Load and call window.open('GenerateFile.aspx?msg=From Clent') from javascript.

+8
source

Instead of calling the web method, it would be better to use a common handler (.ashx file) and put your code to load the file in the ProcessRequest method of the handler.

+3
source

This is an 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 () { } }); }); 

Code for 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; } 
+2
source

All Articles