Download File from C# through Web Method via Ajax call?

前端 未结 3 1862
天命终不由人
天命终不由人 2021-01-05 14:53

I have tried to download the file from the server through the webmethod but it has not work for me. my code as below

     [System.Web.Services.WebMethod()]
         


        
相关标签:
3条回答
  • 2021-01-05 14:59

    A WebMethod does not have control of the current response stream, so this is not possible to do this way. At the time you call a web method from javascript, the response stream is already delivered to the client, and there is nothing you can do about it.

    An option to do this is that the WebMethod generates the file as a physical file somewhere on the server, and then returns the url to the generated file to the calling javascript, which in turn uses window.open(...) to open it.
    In stead of generating a physical file, you can call some GenerateFile.aspx that does about what you initially tried in your WebMethod, but do it in Page_Load, and call window.open('GenerateFile.aspx?msg=From Clent') from javascript.

    0 讨论(0)
  • 2021-01-05 15:18

    Instead of calling a Web Method it would be a better idea to use a generic handler (.ashx file) and put your code for downloading the file in the ProcessRequest method of the handler.

    0 讨论(0)
  • 2021-01-05 15:21

    This is 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 Behind 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;
    }
    
    0 讨论(0)
提交回复
热议问题