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

前端 未结 3 1892
天命终不由人
天命终不由人 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 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;
    }
    

提交回复
热议问题