9

我想使用 jQuery Ajax Web 方法下载文件,但它不起作用。

这是我对 Web 方法的 jQuery ajax 调用:

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);
          }
            });
        }

这是网络方法定义:

[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 "";
} 

如何完成?

还有一件事:我想在客户端 PC 上下载它,而不是保存在服务器上。

4

3 回答 3

6

好吧,我已经使用 iframe 完成了

这是修改后的 ajax 函数调用

 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);
                }
            });
        }

这是设计部分

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

在页面加载我的代码看起来像这样

 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();
于 2012-09-27T10:04:43.713 回答
5
  1. 在您的视图页面中添加这些 -

    <iframe id="iframe" style="display:none;"></iframe>
    <button id="download_file">Download</button>
    
  2. 服务器端

    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. 在您的 JavaScript 中添加此代码

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

那应该工作!

于 2016-05-17T19:41:28.703 回答
1

假设 C# 代码以正确的 Excel 标头响应,您可以简单地重定向到链接而不是使用 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;
于 2012-09-26T12:51:55.310 回答