10

I want to download a file using jQuery Ajax web method, but it's not working.

Here is my jQuery ajax call to web method:

function GenerateExcel() {
   var ResultTable = jQuery('<div/>').append(jQuery('<table/>').append($('.hDivBox').find('thead').clone()).append($('.bDiv').find('tbody').clone()));
   var list = [$(ResultTable).html()];
   var jsonText = JSON.stringify({ list: list });
   $.ajax({
          type: "POST",
          url: "GenerateMatrix.aspx/GenerateExcel",
          data: jsonText,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (response) {

          },
          failure: function (response) {
               alert(response.d);
          }
            });
        }

and this is the web method definition:

[System.Web.Services.WebMethod()]
public static string GenerateExcel(List<string> list)
{
    HttpContext.Current.Response.AppendHeader("content-disposition", "attachment;filename=FileEName.xls");
    HttpContext.Current.Response.Charset = "";
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
    HttpContext.Current.Response.Write(list[0]);
    HttpContext.Current.Response.End();
    return "";
} 

How to get it done?

One more thing: I want to download it on client PC, not to save it on server.

halfer
  • 19,824
  • 17
  • 99
  • 186
rahul
  • 7,573
  • 7
  • 39
  • 53
  • What happens if you go to the link directly (without ajax)? – Lian Sep 26 '12 at 12:31
  • See these posts: http://stackoverflow.com/questions/1944241/ajax-request-to-download-an-excel-file-is-showing-me-truncated-response http://stackoverflow.com/questions/1095102/how-do-i-load-binary-image-data-using-javascript-and-xmlhttprequest – Max Sep 26 '12 at 12:32
  • @Lian i can't go to link directly because i have to send html from client side – rahul Sep 26 '12 at 12:38
  • You can have a look at that question that may help http://stackoverflow.com/a/9834261/1026611 – Mohamed Salah Sep 26 '12 at 13:00

3 Answers3

5

well i have done it using iframe

this is the modified ajax function call

 function GenerateExcel() {
            var ResultTable = jQuery('<div/>').append(jQuery('<table/>').append($('.hDivBox').find('thead').clone()).append($('.bDiv').find('tbody').clone()));
            var list = [$(ResultTable).html()];
            var jsonText = JSON.stringify({ list: list });
            $.ajax({
                type: "POST",
                url: "GenerateMatrix.aspx/GenerateExcel",
                data: jsonText,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (isNaN(response.d) == false) {
                        $('#iframe').attr('src', 'GenerateMatrix.aspx?ExcelReportId=' + response.d);
                        $('#iframe').load();
                    }
                    else {
                        alert(response.d);
                    }
                },
                failure: function (response) {
                    alert(response.d);
                }
            });
        }

and this is the design part

 <iframe id="iframe" style="display:none;"></iframe>

on Page load my code looks like this

 Response.AppendHeader("content-disposition", "attachment;filename=FileEName.xls");
 Response.Charset = "";
 Response.Cache.SetCacheability(HttpCacheability.NoCache);
 Response.ContentType = "application/vnd.ms-excel";
 Response.Write(tableHtml);
 Response.End();
rahul
  • 7,573
  • 7
  • 39
  • 53
  • Hi @rahul, your method is what I am looking for, but I got so confused with when the .hDivbox, b.Div, and table structure? Is in the opener window? I set the Iframe to display:block and did not anything. Thanks – Milacay Mar 14 '16 at 21:29
5
  1. Add these in your view page-

    <iframe id="iframe" style="display:none;"></iframe>
    <button id="download_file">Download</button>
    
  2. Server side

    public string Download(string file)        
    {
    
        string filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["FileManagementPath"]);
    
    
        string actualFilePath = System.IO.Path.Combine(filePath, file);
        HttpContext.Response.ContentType = "APPLICATION/OCTET-STREAM";
        string filename = Path.GetFileName(actualFilePath);
        String Header = "Attachment; Filename=" + filename;
        HttpContext.Response.AppendHeader("Content-Disposition", Header);           
        HttpContext.Response.WriteFile(actualFilePath);
        HttpContext.Response.End();
        return "";
    }
    
  3. Add this code in your JavaScript

    <script>
    
        $('#download_file').click(function(){
    
            var path = 'e-payment_format.pdf';//name of the file
            $("#iframe").attr("src", "/FileCabinet/Download?file=" + path);
    
        });
    
     </script>
    

That should work!

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
1

Assuming the C# code responds with the correct headers for Excel, you can simply redirect to the link instead of using ajax:

var list = [$(ResultTable).html()];
var url = "GenerateMatrix.aspx/GenerateExcel";
var data = {list: list};
url += '?' + decodeURIComponent($.param(data));

// if url is an excel file, the browser will handle it (should show a download dialog)
window.location = url;
Lian
  • 2,197
  • 2
  • 15
  • 16