If you find this article useful, consider making a small donation to show your support for this web site and its content.
DiscountASP
AboutMe
About me:
Hi. My name is Farooq Kaiser and I'm a software developer from Toronto, Canada.

Did you know.. How to download file from web service using JavaScript or Jquery?

by Farooq Kaiser 23. February 2010 07:14

Here is our Web service in C#.

   1: [WebMethod]
   2: public void DownloadFile(string fileName)
   3: {
   4:     HttpContext returnContext = HttpContext.Current;
   5:     string url = "http://localhost" + @"/" + fileName;
   6:     
   7:     FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
   8:     ftpRequest.Credentials = new NetworkCredential(UserId, UserPassword);
   9:     ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
  10:     
  11:     using (FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
  12:     {
  13:     
  14:         using (Stream stream = ftpResponse.GetResponseStream())
  15:         {
  16:     
  17:                 returnContext.Response.Clear();
  18:                 returnContext.Response.ClearHeaders();
  19:                 returnContext.Response.ClearContent();
  20:                 returnContext.Response.ContentType = "application/octet-stream";
  21:                 returnContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
  22:     
  23:                 byte[] bytes = new byte[8192];
  24:                 int bytesRead = 0;
  25:     
  26:                 while ((bytesRead = stream.Read(bytes, 0 , bytes.Length)) > 0 )
  27:                 {
  28:                     returnContext.Response.OutputStream.Write(bytes, 0, bytesRead); 
  29:                 }
  30:         }
  31:     }
  32: }

 

Here is JavaScript function using Jquery to download file.

   1: <html xmlns="http://www.w3.org/1999/xhtml" >
   2: <head>
   3:   <title>Download Page</title>
   4: <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
   5: <script type="text/javascript"> 
   6:  function FileDownload()
   7:  {
   8:      var inputs ='<input type="hidden" name="fileName" value="'+ document.getElementById("fileName").value +'" />';   
   9:      jQuery('<form action="http://localhost/DownloadService.asmx/DownloadFile" method="post">'+inputs+'</form>')
  10:     .appendTo('body').submit().remove();
  11:  }
  12: </script>
  13: </head>
  14: <body>
  15: File Name <br />
  16:  <input id="fileName" name="fileName" type="text" />
  17:  <input id="Download" type="button" onclick="return FileDownload();"  value="Download File"  />
  18: </body>
  19: </html>

Please feel free to leave any comments. Thanks.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , , ,

Did you know

Comments

Jobs Autos Real estate Videos Power by Google