编码AJAX二进制响应 [英] Encoding AJAX binary response

查看:82
本文介绍了编码AJAX二进制响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





这是之前在其他地方发布的问题的扩展。



我有编写了一些对PHP函数执行POST的AJAX。 PHP函数以二进制格式返回PDF文档。



我遇到的问题是浏览器中的结果是Pdf文件下载损坏率约为160%文件大小比它应该大。最初,我怀疑这是PHP特有的问题,但我现在倾向于更多地关注如何通过AJAX代码处理二进制数据,特别是使用8-来传递响应。位编码可能在客户端预期/正在使用16位编码。我试图从各个角度看待这个问题,而不仅仅是寻找光线好的地方。



相关的PHP函数可以在这里看到:



http://stackoverflow.com/questions/28662081/output-pdf-data-from-array-variable-to-output-stream-in-php [ ^ ]



这是AJAX:





Hi,

This is an extension to a question previously posted elsewhere.

I have coded some AJAX that performs a POST to a PHP function. The PHP function returns a PDF document in binary format.

The problem I am experiencing is that the result in the browser is a corrupted Pdf file download that is about 160% larger in file size than it should be. Originally, I suspected this was an issue specific to PHP, but I'm now leaning toward the possibility that it is more to do with how the binary data is processed by the AJAX code, and specifically that the response is delivered using a 8-bit encoding where perhaps a 16-bit encoding is expected/in-use on the client-side. I am trying to look at this problem from all angles rather than just "searching where the light is good".

The relevant PHP functions can be seen here:

http://stackoverflow.com/questions/28662081/output-pdf-data-from-array-variable-to-output-stream-in-php[^]

And this is the AJAX:


$(document).ready(function(){

    $("#dwnAS").click(function(d){
        d.preventDefault();

        var ASreqtype = "AS";
        var ASfooterLine1 = $("#footerText1").val();
        var ASfooterLine2 = $("#footerText2").val();
        var ASfooterLine3 = $("#footerText3").val();
        var AStableHeaderLine  = $("#tableCaption").val();
        var ASquizTitle = $("#quizTitle").val();
        var ASwithCues  = $("#withCues").val();

        if (ASquizTitle=='')
        {
            alert("Please specify a quiz title");
        }
        else
        {
            //disable the submission controls
            $("#dwnAS").attr("disabled", true);
            $("#dwnMS").attr("disabled", true);
            $("#dwnTB").attr("disabled", true);

            var postData =
                'type=' + ASreqtype
                + '&quizId=' + '<?php echo $quizId; ?>'
                + '&footerLine1=' + encodeURIComponent(ASfooterLine1)
                + '&footerLine2=' + encodeURIComponent(ASfooterLine2)
                + '&footerLine3=' + encodeURIComponent(ASfooterLine3)
                + '&tableHeaderLine=' + encodeURIComponent(AStableHeaderLine)
                + '&quizTitle=' + encodeURIComponent(ASquizTitle)
                + '&contentLicensedToName=' + '<?php echo urlencode($contentLicensedToName) ; ?>'
                + '&locale=' + '<?php echo $locale; ?>'
                + '&withCues=' + ASwithCues
                + '&authId=' + '<?php echo urlencode($authId); ?>' ;

            // AJAX Code To Submit Form.
            $.ajax({
                type: "POST",
                url: "subscriber-download-post.php",
                data: postData,
                cache: false,
                success: function(response, status, xhr){

                    $("#dwnAS").attr("disabled", false);
                    $("#dwnMS").attr("disabled", false);
                    $("#dwnTB").attr("disabled", false);

                    downloadresponse(response, status, xhr);



                },
                error: function(response){
                    $("#dwnAS").attr("disabled", false);
                    $("#dwnMS").attr("disabled", false);
                    $("#dwnTB").attr("disabled", false);

                    alert("The download failed. Please try again later.");
                }
            });
        }
    }
)
}) //$(document).ready(function(){

function downloadresponse(response, status, xhr) {
        // check for a filename
        var filename = "";
        var disposition = xhr.getResponseHeader('Content-Disposition');
        if (disposition && disposition.indexOf('attachment') !== -1) {
            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            var matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
        }

        var type = xhr.getResponseHeader('Content-Type');
        var blob = new Blob([response], { type: type });

        if (typeof window.navigator.msSaveBlob !== 'undefined') {
            // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
            window.navigator.msSaveBlob(blob, filename);
        } else {
            var URL = window.URL || window.webkitURL;
            var downloadUrl = URL.createObjectURL(blob);

            if (filename) {
                // use HTML5 a[download] attribute to specify filename
                var a = document.createElement("a");
                // safari doesn't support this yet
                if (typeof a.download === 'undefined') {
                    window.location = downloadUrl;
                } else {
                    a.href = downloadUrl;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                }
            } else {
                window.location = downloadUrl;
            }

            setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
        }
}







我有遇到这篇文章..

http:// stackoverflow。 com / questions / 8022425 / getting-blob-data-from-xhr-request [ ^ ]

触及AJAX如何处理二进制数据响应以及如何通过执行某些操作来处理它喜欢...






I have come across this article..
http://stackoverflow.com/questions/8022425/getting-blob-data-from-xhr-request[^]
which touches upon how AJAX handles the binary data response and how it may be possible to deal with it by doing something like ...

var uInt8Array = new Uint8Array(this.response);





- 但我不太清楚如何将它们放在一起。看起来我可能需要完全将其从ajax请求更改为xhr请求,如果无法通过调整现有代码来处理编码问题?



假设编码不匹配确实是问题,我也很满意我可以在PHP端应用的修复,即使这意味着要做一些额外的编码工作在运行时。



如果我不能解决这个问题,我也在考虑放弃我目前的方法,并重新设计整个使用相应的临时URL生成临时文档,然后根据请求重新定向浏览器的事情。只是觉得这样的耻辱,因为我确信它必须能够使这个设计工作,而且我已经非常接近。



任何建议都会非常感激。



- but I can't quite see how to put it all together. It looks like I may need to completely change this from an "ajax" request to an "xhr" request, if there is no way to handle the encoding issue with adjustments to the existing code?

Assuming that an encoding mismatch is indeed the issue, I'd also be happy with a fix that I can apply on the PHP-side, even if that means doing some extra encoding work at run-time.

If I can't work this out, I'm also considering abandoning my current approach, and re-designing the whole thing to generate temporary documents with a corresponding temporary URL, and then just re-directing the browser per-request. It would just feel like such a shame, as I'm sure it must possible to make this design work, and I've gotten awfully close.

Any advice would be gratefully appreciated.

推荐答案

(document).ready(function(){
(document).ready(function(){


#dwnAS)。click(function(d){
d.preventDefault();

var ASreqtype = AS ;
var ASfooterLine1 =
("#dwnAS").click(function(d){ d.preventDefault(); var ASreqtype = "AS"; var ASfooterLine1 =


< span class =code-string>#footerText1)。val();
var ASfooterLine2 =
("#footerText1").val(); var ASfooterLine2 =


这篇关于编码AJAX二进制响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆