How to download file via jQuery ajax and C#

后端 未结 3 2063
悲哀的现实
悲哀的现实 2020-12-16 20:46

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() {         


        
相关标签:
3条回答
  • 2020-12-16 21:17

    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;
    
    0 讨论(0)
  • 2020-12-16 21:33
    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!

    0 讨论(0)
  • 2020-12-16 21:42

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