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

4

7

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()]
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 as 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 have called this function in button click..

i don't know how to download the file with other methods

Please suggest me if any other methods available or give the correction in the same code.

Thanks to all..

Rettke answered 23/8, 2012 at 7:47 Comment(0)
M
10

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.

Manoeuvre answered 23/8, 2012 at 7:54 Comment(0)
J
3

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.

Jocelin answered 24/8, 2012 at 10:9 Comment(0)
W
1

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;
}
Waylin answered 30/10, 2014 at 15:35 Comment(5)
Can you write more explanation?Revolving
which part of this code you want to know more? i will give you explanationWaylin
File is not able to download. :(Hypogene
Check your file is exists on that path or give all access to that folderWaylin
It gives Thread was being aborted exception Response.End() and it sends StackTrace in response. Did it work for anyone?Dualism
W
1

do so:

This is Ajax

var request = new XMLHttpRequest(), file, fileURL;
request.open("POST", URL);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.responseType = "arraybuffer";
request.send('{D: ' + JSON.stringify(F) + '}');
request.onreadystatechange = function () {
    if (request.readyState === 4 && request.status === 200) {
        file = new Blob([request.response], { type: 'application/octet-stream' });
        if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE
            window.navigator.msSaveOrOpenBlob(file);
        } else {
            fileURL = URL.createObjectURL(file);
            window.open(fileURL);
        }
    }
};

server side

    [WebMethod]
   public static string DownloadDoc(string id)
   {
       byte[] btFile // The file bytes            
        HttpContext.Current.Response.BinaryWrite(btFile);         
        return "";
    }
Wondrous answered 11/4 at 13:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.