如何通过jQuery ajax和C#下载文件

10

我想使用jQuery Ajax web方法下载文件,但是它没有起作用。

这是我的jQuery ajax调用web方法:

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

这是Web方法的定义:

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

如何完成?

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


如果您直接访问链接(而不是通过Ajax),会发生什么? - Lian
请查看以下帖子:https://dev59.com/TkrSa4cB1Zd3GeqPafLahttps://dev59.com/mnNA5IYBdhLWcg3wF5uO - Max
@Lian 我无法直接访问链接,因为我必须从客户端发送HTML。 - rahul
你可以看一下这个问题,它可能有所帮助:https://dev59.com/Q2865IYBdhLWcg3wkfcW#9834261 - Mohamed Salah
3个回答

5
我用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();

嗨@rahul,你的方法正是我所需要的,但是我对.hDivbox、b.Div和table结构在打开的窗口中的位置感到非常困惑。我将Iframe设置为display:block,但没有任何效果。谢谢。 - Milacay

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>
    

那应该可以工作!


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;

Web方法会保持不变吗? - rahul
我不知道你的输出是什么。请查看此链接:https://dev59.com/cXNA5IYBdhLWcg3wZ9DU - Lian
我正在使用相同的东西,但是你的答案对我不起作用。 - rahul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接