jquery - 如何从 byte[] 中的 webmethod 下载 javascript 或 jquery 中的文件?

标签 jquery asp.net ajax c#-4.0

我在使用 jquery 下载 Excel 文件时遇到问题。我在一些论坛上读到,使用 ajax 是不可能实现这一点的,在一些论坛上他们说你可以通过将结果发送到 iframe 来实现这一点。到目前为止我还没有能够解决我的问题。

技术细节: 我使用一些参数生成对数据库的查询,Web 服务执行此查询并返回在 openxml 中生成的 excel 文件并返回字节。 我使用的是asp.net 4.0。 如果我使用常规的 webcontrols 和 ajax,如果在更新面板中我将触发器设置为 asp:postbacktrigger 到按钮控件,则文件下载不会有问题。

我试图仅使用 jqueryUi 控件和 jquery 来实现相同的结果。

在服务器端我有两种方法:

导出到Excel: 此方法接收参数以调用返回 excelfile 的其余 Web 服务。

按字节发送Excel文件 这个是在请求中返回文件的方法。

这是 C# 代码:

[WebMethod]
    public static void ExportToExcel(List<int> status, List<Guid> companyId, List<DateTime> dateFrom, List<DateTime> dateTo, bool isGroupedByStore)
    {
        ReconciliationModule server = new ReconciliationModule(ConfigurationManager.AppSettings["serviceNamespace"], ConfigurationManager.AppSettings["ACSHostUrl"], ConfigurationManager.AppSettings["scopeAddress"]);
        SummaryReport summaryReport = new SummaryReport();

        List<Tuple<Guid, DateTime, DateTime, int>> parameters = new List<Tuple<Guid, DateTime, DateTime, int>>();

        for (int i = 0; i < dateTo.Count; i++)
        {
            parameters.Add(new Tuple<Guid, DateTime, DateTime, int>(
                companyId[i],
                dateFrom[i],
                dateTo[i],
                status[i]
            ));
        }

        byte[] x = server.GetSummaryReportInExcel(ConfigurationManager.AppSettings["userName"], ConfigurationManager.AppSettings["pwdOrSymmetricKey"], bool.Parse(ConfigurationManager.AppSettings["isSymmetricKey"]), isGroupedByStore, parameters);

        SendExcelFileByBytes(x);
    }

    private static void SendExcelFileByBytes(byte[] x)
    {
        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"SummaryReport.xlsx\"");
        System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "application/force-download");
        System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "application/download");
        //System.Web.HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
        System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";//excel file
        System.Web.HttpContext.Current.Response.Clear();

        System.Web.HttpContext.Current.Response.BinaryWrite(x);
        //System.Web.HttpContext.Current.Response.Close();
        System.Web.HttpContext.Current.Response.Flush();
        System.Web.HttpContext.Current.Response.End();
    }

对于 jscript,我的 callAjaxFunction 失败并返回 200 OK 消息,结果在响应文本中。因此,在出现故障时执行的函数中,我在表中显示响应文本。 如果有人可以帮助我以更好的方式做到这一点,我将不胜感激。 这是 jscript 代码:

//Executes Ajax Calls using json as data type
function callAjax(callType, urlAddress, dataToSend, fnSucceeded, fnFailed) {
    $.ajax({
        type: callType,
        url: urlAddress,
        contentType: "application/json; charset=utf-8",
        data: dataToSend,
        dataType: "json",
        success: fnSucceeded,
        error: fnFailed
    });
}

//TODO: This function is the one i need to correct
function getSummaryReportInExcel() {

    ShowLoader('#reconciliation');
    var isGroupedByStore = new Boolean($('#CompanyTypes :checkbox').attr('checked'));
    var stat = getStatus();
    var status = new Array();
    var companyId = new Array();
    var dateFrom = new Array();
    var dateTo = new Array();
    var companiesToSearch = $('#CompanyConfigurations :checkbox:checked');

    //populating the parameters
    $(companiesToSearch).each(function (i, currentCompany) {
        status.push(stat);
        companyId.push($(currentCompany).select('checkbox').attr('value'));
        dateFrom.push($(currentCompany).parents().find('td:eq(2) :input').attr('value'));
        dateTo.push($(currentCompany).parents().find('td:eq(3) :input').attr('value'));
    });

    var data = "{ status : " + JSON.stringify(status) + ", companyId : " +  JSON.stringify(companyId) + ", dateFrom : " +  JSON.stringify(dateFrom) + ", dateTo : " +  JSON.stringify(dateTo) + ", isGroupedByStore : " + isGroupedByStore + " }";

    alert(data);

    callAjax(
        "POST", "UIJquery.aspx/ExportToExcel",
        data,
        //is not entering here
        function () {
            alert('Hola' + result.toString());

            //header.
            HideLoader();
        },
        //AjaxFailed
        function (result) {
            //alert(concatObject( result));
            $('#SearchResults').append(concatObject(result));
            //var iFrame = "<iframe src=" + result.responseText + "></iframe>";


            $('#IResults').html(result.responseText);
            //window.open(result.responseText, 'Download');
            HideLoader();
            //alert(concatObject(result));
        }
    );
}

这是我在 google chrome 开发者工具中看到的内容

HeadersPreviewResponseTiming
Request URL:http://localhost:53144/UIJquery.aspx/ExportToExcel
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:216
Content-Type:application/json; charset=UTF-8
Host:localhost:53144
Origin:http://localhost:53144
Referer:http://localhost:53144/UIJQuery.aspx
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.83 Safari/535.11
X-Requested-With:XMLHttpRequest
Request Payload
{ status : [15,15], companyId : ["15afbacb-5c0c-4402-a5af-0f5a53221bbb","041d6a48-35ca-4d55-97ec-4fd5f4bdd11f"], dateFrom : ["11/06/2011","11/06/2011"], dateTo : ["11/12/2011","11/12/2011"], isGroupedByStore : true }
Response Headersview source
Cache-Control:private, max-age=0
Connection:Close
Content-Disposition:attachment; filename="SummaryReport.xlsx"
Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Date:Wed, 28 Mar 2012 18:22:32 GMT
Server:ASP.NET Development Server/10.0.0.0
Transfer-Encoding:chunked
X-AspNet-Version:4.0.30319

任何建议或更好的方法请告诉我,谢谢。

最佳答案

类似的事情......

<script type="text/javascript">
function downloadExcelFile(url, dataToSend) {
   url += '?';
   for(var k in dataToSend) {
      url += k + '=' + encodeURIComponent(dataTosend[k]) + '&';
      }
   window.location = url;
   }
</script>

这会将基本 url 作为第一个参数,并使用包含参数的对象作为第二个参数,从中构造一个完整的 url 并将浏览器重定向到它...例如

downloadExcelFile('http://www.example.com/myWebservice/downloadExcel.aspx', {
   param1: 'value1',
   param2: 'value2'
   });

在这种情况下,浏览器将被重定向到

http://www.example.com/myWebservice/downloadExcel.aspx?param1=value1&param2=value2&

关于jquery - 如何从 byte[] 中的 webmethod 下载 javascript 或 jquery 中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9913758/

相关文章:

javascript - 刷新表格而不刷新整个页面以显示更新的数据

php - 使用 php、json 和 jquery 插入数据库

javascript - 可在特定的 div 内拖动

javascript - jquery可以用ajax执行整个html吗?

javascript - AJAX循环完成后执行代码

javascript - DDSlick 'selected' 在 <select> 元素上忽略属性

javascript - AngularJS - 绑定(bind)父级以触发子级的 Angular 方式

c# - String.replace 删除反斜杠

c# - 设置用户控件以监听基础类库中的更新

jquery - 良好的 DRY 方法来渲染和 AJAX 更新页面