如何在 jquery .post 中将二进制文件保存在客户端上

发布于 2024-12-06 21:17:48 字数 3027 浏览 0 评论 0原文

我有带有以下代码的处理程序:

    HttpRequest request = context.Request;
    HttpResponse response = context.Response;

    if (request["Type"] != null)
    {
        try
        {
            string resultFile = null;
            string fileName = string.Empty;

            int type = Convert.ToInt32(request["Type"]);

            switch (type)
            {
                case 1:
                    fileName = "InnerQuery.doc";
                    resultFile = GenerateInnerQuery(Id);
                    break;

                case 2:
                    fileName = "CourierQuery.doc";
                    resultFile = GenerateCourierQuery(Id);
                    break;

                case 3:
                    fileName = "TransportDogovor.doc";
                    resultFile = GenerateTransportDogovor(Id);
                    break;

                case 4:
                    fileName = "TransportQuery.doc";
                    resultFile = GenerateTransportQuery(Id);
                    break;

                case 5:
                    fileName = "PassQuery.doc";
                    resultFile = GeneratePassQuery(Id);
                    break;
            }

            if (resultFile != null)
            {
                response.Clear();
                response.AddHeader("pragma", "no-cache");
                response.AddHeader("cache-control", "private");
                response.CacheControl = "no-cache";
                response.ContentType = "application/octet-stream";
                response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}",
                    System.Web.HttpUtility.UrlPathEncode(fileName)));
                response.OutputStream.Write(File.ReadAllBytes(resultFile), 0, (int)(new FileInfo(resultFile)).Length);
                response.End();
            }
        }
        catch (Exception ex)
        { }
    }

在客户端上,我使用 jQuery.post() 将数据发布到处理程序:

var handler = "GetWord.ashx?Type=6";
    var initiationDateFrom = $("#<%=InitiationDateFromTxt.ClientID%>").val();
    var initiationDateTill = $("#<%=InitiationDateTillTxt.ClientID%>").val();
    var queryDateFrom = $("#<%=QueryDateFromTxt.ClientID%>").val();
    var queryDateTill = $("#<%=QueryDateTillTxt.ClientID%>").val();
    var queryNumber = $("#<%=NumberTxt.ClientID%>").val();
    var initiator = $("#<%=InitiatorTxt.ClientID%>").val();
    var state = $("#<%=StateList.ClientID%>").val();
    $.post(handler,
    {
        InitiationDateFrom: initiationDateFrom,
        InitiationDateTill: initiationDateTill,
        QueryDateFrom: queryDateFrom,
        QueryDateTill: queryDateTill,
        QueryNumber: queryNumber,
        Initiator: initiator,
        State: state
    }, function (data) {
       /*here i should save my file*/
    });

我收到“数据”中的二进制字文件,但无法将其保存在客户端上。

上次我使用:

window.location = handler;

但是使用 jQuery.post 它不起作用。

I have handler with this code:

    HttpRequest request = context.Request;
    HttpResponse response = context.Response;

    if (request["Type"] != null)
    {
        try
        {
            string resultFile = null;
            string fileName = string.Empty;

            int type = Convert.ToInt32(request["Type"]);

            switch (type)
            {
                case 1:
                    fileName = "InnerQuery.doc";
                    resultFile = GenerateInnerQuery(Id);
                    break;

                case 2:
                    fileName = "CourierQuery.doc";
                    resultFile = GenerateCourierQuery(Id);
                    break;

                case 3:
                    fileName = "TransportDogovor.doc";
                    resultFile = GenerateTransportDogovor(Id);
                    break;

                case 4:
                    fileName = "TransportQuery.doc";
                    resultFile = GenerateTransportQuery(Id);
                    break;

                case 5:
                    fileName = "PassQuery.doc";
                    resultFile = GeneratePassQuery(Id);
                    break;
            }

            if (resultFile != null)
            {
                response.Clear();
                response.AddHeader("pragma", "no-cache");
                response.AddHeader("cache-control", "private");
                response.CacheControl = "no-cache";
                response.ContentType = "application/octet-stream";
                response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}",
                    System.Web.HttpUtility.UrlPathEncode(fileName)));
                response.OutputStream.Write(File.ReadAllBytes(resultFile), 0, (int)(new FileInfo(resultFile)).Length);
                response.End();
            }
        }
        catch (Exception ex)
        { }
    }

On client i post data to handler with jQuery.post():

var handler = "GetWord.ashx?Type=6";
    var initiationDateFrom = $("#<%=InitiationDateFromTxt.ClientID%>").val();
    var initiationDateTill = $("#<%=InitiationDateTillTxt.ClientID%>").val();
    var queryDateFrom = $("#<%=QueryDateFromTxt.ClientID%>").val();
    var queryDateTill = $("#<%=QueryDateTillTxt.ClientID%>").val();
    var queryNumber = $("#<%=NumberTxt.ClientID%>").val();
    var initiator = $("#<%=InitiatorTxt.ClientID%>").val();
    var state = $("#<%=StateList.ClientID%>").val();
    $.post(handler,
    {
        InitiationDateFrom: initiationDateFrom,
        InitiationDateTill: initiationDateTill,
        QueryDateFrom: queryDateFrom,
        QueryDateTill: queryDateTill,
        QueryNumber: queryNumber,
        Initiator: initiator,
        State: state
    }, function (data) {
       /*here i should save my file*/
    });

I recieve binary word-file in "data", but can't to save it on client.

last time i use:

window.location = handler;

but with jQuery.post it not work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

紫南 2024-12-13 21:17:48

我认为这个问题的答案需要一些更新

我遇到了以下库: https://github.com/eligrey/FileSaver.js

另外,就我而言,它很简单,如下所示:

至少这是适合我的解决方案,我只需要支持它铬(v37)。

前言:

我需要通过post请求下载excel文件。以下是我在阅读了一些规格和问答后解决这个问题的方法。

在我的 ajax 调用设置中,我将响应类型设置为“blob”:

'responseType': 'blob'

一旦收到成功的响应,您将需要进行一些小的 DOM 欺骗来触发下载,如下所示:

var downloadLink = document.createElement('a');
downloadLink.download = 'export.xlsx';
downloadLink.innerHTML = 'Download File';
downloadLink.href = window.webkitURL.createObjectURL(data);
downloadLink.click();

THIS QUESTION's ANSWERS NEEDS A BIT OF AN UPDATE I THINK

I have come across following library: https://github.com/eligrey/FileSaver.js

Also in my case it was as simple as following:

At least here is the solution that works for me and i only needed to support it in chrome (v37).

Preface:

I needed to download excel file via post request. So here is how I have tackled it after reading up on few specs and q&as.

In my ajax call set up, i set response type to 'blob':

'responseType': 'blob'

And once successful response is received you would need to do minor DOM trickery to trigger download as follows:

var downloadLink = document.createElement('a');
downloadLink.download = 'export.xlsx';
downloadLink.innerHTML = 'Download File';
downloadLink.href = window.webkitURL.createObjectURL(data);
downloadLink.click();
山色无中 2024-12-13 21:17:48

当您使用 AJAX 请求请求数据时,您需要在 JavaScript 中处理它。保存文件将不可用。

您需要创建一个保存参数的表单,而不是使用 AJAX 请求。使用 target 属性将响应定向到隐藏的 iframe,浏览器将提供保存文件的功能。

When you request the data with an AJAX request, you need to handle it in JavaScript. Saving a file will not be available.

Instead of using an AJAX request you need to create a form that holds your parameters. Direct the response into an hidden iframe using the target attribute and the browser will offer to save the file.

话少心凉 2024-12-13 21:17:48

如上所述,有多种不同的方法。您可能需要先查看 jQuery 文件上传

其次,您可能需要查看解决方案中包含 flash 的几个选项( uploadifyswfupload)。我过去曾使用过这两种产品,它们令人满意地满足了我的需求,但并不完美。

As mentioned above, there are a number of different approaches. You may want to look at jQuery File Upload first.

Secondarily, you may want to look at a couple of options that include flash in the solution ( uploadify or swfupload). I have used both in the past and they met my needs satisfactorily - but not perfectly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文