如何将ajax blob responseText转换为文件到Javascript中

时间:2015-12-09 05:36:13

标签: javascript

我有一个从服务器下载文件的ajax功能。

$.ajax({
        method: "POST",
        url: postUrl,
        data: jsonData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) { alert("success"); },
        error: function (xhr, ajaxOptions, thrownError) {
            debugger;
            var blob = new Blob([xhr.responseText]);

        },
        beforeSend: function () {
            // Handle the beforeSend event
            $("#progresscontainer").show();
        },
        complete: function () {
            // Handle the complete event
            $("#progresscontainer").hide();
        }
    });

    return false;
}

Ajax服务器(C#代码)调用 GetFile 最终导致Ajax错误(不确定原因),但我可以看到 xhr.responseText 中的内容。现在我如何转换这个实际上是文件的内容。因此用户可以打开文件(与我们点击下载文件链接一样,下载实际文件)。这里我的文件返回到xhr.responseText

    private static void GetFile(byte[] file, string FileName)
{
    if (file.Length > 0)
    {

        HttpContext.Current.Response.AddHeader("content-length", file.Length.ToString());
        HttpContext.Current.Response.AddHeader("X-Content-Type-Options", "nosniff");
        HttpContext.Current.Response.BinaryWrite(file);
        HttpContext.Current.Response.End();
        //HttpContext.Current.Response.End();
        HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
        HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
        HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
    }
}

xhr.responseText

"%PDF-1.7 
%���� 
1 0 obj 
<< 
/Type /Catalog 
/Pages 2 0 R 
/PageMode /UseNone 
/ViewerPreferences << 
/FitWindow true 
/PageLayout /SinglePage 
/NonFullScreenPageMode /UseNone 
>> 
>> 
endobj 
5 0 obj 
<< 
/Length 510 
/Filter [ /FlateDecode ] 
>> 
stream
x�e�K��0������E+�m�+�<�iF�W�.]�th�90-��C�!B���\��w�J�8
/0���[�^"
~�Q
,b��c�� #�gOy+���ǡ$�  ����h��]�x��Y���|���)F1�һ���a�7�ةKk�*$|mJX��$0 �1��L$�k�)��Ǔ<��v�,���;&�uC��28�   �����g�UY�c����
b؈�dY��uc����ykt�J�\km k�2�����ZX���H�}�����l�w� ;>Ŕ�(��|-�1�_�.���4Z�n@��%x`����k�Zb��rȍ�������R�T�t���*��e���d��G1a3�.��0C!���cQ���m��̿�kcsl`-L9�    �Am�4��l4�$FbE�*�o�t/6b�4p�I�M���    v���X̻w"���*.��9�צm��]��E�s`<�6��-׍=7��n�l�����r��#�H<�"����F6��/~��?�q��endstream 
endobj 
12 0 obj 
<< 
/Length 438 
/Filter [ /FlateDecode ] 
>> 

0 个答案:

没有答案