首页 > 解决方案 > 如何组合通过 API 中的 get 函数检索到的二进制 (PDF-) 文件块

问题描述

我编写了一个使用xmlhttprequest-ts的函数,应该有助于从 api 异步获取 pdf。

然后该 PDF 被发送到前端,不幸的是它显示为空。我猜想我需要以某种方式合并我收到的单个数据块,但在尝试了多种方法后我不知道该怎么做。

例如 Buffer.from() + Buffer.concat() 导致在 promise 解决后打印出一个空的缓冲区。我拥有的看似最接近的解决方案如下,我只是在其中添加了一个二进制字符串:

export async function getFile(resourceUrl: string, apiPath: string, responseType:string, token?: string, basicId?:string, apiKey?:string,  ): Promise<any>{
  try {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();

    xhr.open("GET", resourceUrl + apiPath, true);
    if(!isNullOrUndefined(apiKey)){
      xhr.setRequestHeader("api-key", apiKey);
    } else if(!isNullOrUndefined( token) && isNullOrUndefined(basicId)){
      xhr.setRequestHeader("Authorization", "Bearer " + token);
    } else if(!isNullOrUndefined( token) && !isNullOrUndefined(basicId)){
      xhr.setRequestHeader("Authorization", "Basic " + Buffer.from(basicId + ":" + token).toString('base64'));
    }

    xhr.setRequestHeader("Accept", responseType);
    
    let binaryString = ""; // initial binary string
    
    xhr.onload =  function (){
        try{
            if (xhr.readyState == 4 && xhr.status == 200 ) {
              console.log("Code: " + xhr.status + ": " + xhr.statusText +  "; Request success"  );
                
              binaryString = binaryString + xhr.responseText; //adding up binary string
            } else {
              console.log("Code: " + xhr.status + ": " +  xhr.statusText + "; "  + xhr.responseText);
              reject(new ErrorModule.xmlHttpServiceError(xhr.responseText, xhr.status , xhr.statusText, xhr.responseText ));
            }
        } catch(err){
          reject(err);
        }
    }

    xhr.onloadend = function (){
        try {
          if (xhr.readyState == 4 && xhr.status == 200 ) {

              resolve(binaryString); // returning binary string
            } else {
              console.log("Code: " + xhr.status + ": " +  xhr.statusText + "; "  + xhr.responseText);
              reject(new ErrorModule.xmlHttpServiceError(xhr.responseText, xhr.status , xhr.statusText, xhr.responseText ));
            }
          } catch(err){
            reject(err);
          }
      }
      
    xhr.send();

    });
} catch(err){
throw new Error(err);
}

}

当我在解析后打印出二进制字符串时,您可以清楚地看到以下模式中的多个块(取自字符串末尾):

C}O�����D.��w�#n]:ީ��qqUX��N+��;�RD����]��}�_ܝ�%�/
                                             �
                                              ˢ)�&quot;�r���L��U�Y�TI(@fu����Y���Z���x�Y+�Үµ-
                                                                                    

    .8d�P�+e�����4��N�    [�
                                                                                                                    ������+��b�Z]�6����D�/�(q�2��0Ӣ�Z�HeA�� ��Y
endstream
endobj
16 0 obj
<</Type /FontDescriptor
/FontName /Arial-BoldMT
/Flags 4
/Ascent 905.27344
/Descent -211.91406
/StemV 76.171875
/CapHeight 715.82031
/ItalicAngle 0
/FontBBox [-627.92969 -376.46484 2033.6914 1047.85156]
/FontFile2 15 0 R>>
endobj
17 0 obj
<</Type /Font
/FontDescriptor 16 0 R
/BaseFont /Arial-BoldMT
/Subtype /CIDFontType2
/CIDToGIDMap /Identity
/CIDSystemInfo <</Registry (Adobe)
/Ordering (Identity)
/Supplement 0>>
/W [0 [750] 3 17 277.83203 21 23 556.15234 40 [666.99219 0 777.83203] 51 [666.99219] 68 [556.15234 610.83984 0 0 556.15234 0 610.83984 0 277.83203 0 0 277.83203 889.16016 610.83984 610.83984 0 0 389.16016 556.15234 333.00781] 93 [500] 188 [556.15234]]
/DW 0>>
endobj
18 0 obj
<</Filter /FlateDecode
/Length 320>> stream
x�]��n�0
        ��<E�ݡ��P6     !1�J�G�{ ��.QH���M;i� ���3v��n�ў�n�-x�k�L��I`g�hq���~%|ˡ�Q��<yӏQQ0�����6�����N����6_u�Z�ϒ�,��>dz��[7 �ѶmT�k?o��Oq�-0�̩9*�l'�u�Q��U��V�Q��|��{��9
��<IDR"�j$Ή^��#R�UD9Ҏ�d�%%垔))��Lk�'�쀔WH�KL$U���5�����
                                                       M<��NP��V��I�d�6���$�s����/G���&gt;yu.��3XN__;�ŵ&lt;�����
endstream
endobj
7 0 obj
<</Type /Font
/Subtype /Type0
/BaseFont /Arial-BoldMT
/Encoding /Identity-H
/DescendantFonts [17 0 R]
/ToUnicode 18 0 R>>
endobj
xref
0 19
0000000000 65535 f
0000000015 00000 n
0000071700 00000 n
0000000154 00000 n
0000000191 00000 n
0000048619 00000 n
0000094566 00000 n
0000109180 00000 n
0000069862 00000 n
0000071953 00000 n
0000072008 00000 n
0000072056 00000 n
0000093141 00000 n
0000093375 00000 n
0000094148 00000 n
0000094698 00000 n
0000108095 00000 n
0000108334 00000 n
0000108789 00000 n
trailer
<</Size 19
/Root 10 0 R
/Info 1 0 R>>
startxref
109317
%%EOF

标签: typescriptpdfgetxmlhttprequest

解决方案


推荐阅读