2016-12-27 10 views
1

내가 타이프 라이터/자바 스크립트에 새로 온 사람과 내가 타이프 라이터와 XMLHttpRequest의를 사용하여 이진 파일의 다른 부분에 대한 다중 범위 요청 (RFC 7233를) 할 노력하고있어 RFC 7233에 따르면 2typescript/javascript를 사용하여 multipart/byteranges 응답을 올바르게 구문 분석하는 방법은 무엇입니까?

, 여러 부분은/응답의 byteranges

HTTP/1.1 206 Partial Content 
Date: Wed, 15 Nov 1995 06:25:24 GMT 
Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT 
Content-Length: 1741 
Content-Type: multipart/byteranges; boundary=THIS_STRING_SEPARATES 

--THIS_STRING_SEPARATES 
Content-Type: application/pdf 
Content-Range: bytes 500-999/8000 

...the first range... 
--THIS_STRING_SEPARATES 
Content-Type: application/pdf 
Content-Range: bytes 7000-7999/8000 

...the second range 
--THIS_STRING_SEPARATES-- 

내가 두 가지 옵션을 참조하십시오 : 다음이

  1. 이진 데이터 배열과 응답 (XMLHttpRequest.responseType = "arraybuffer" 설정)의 몸을 치료를 비나에 경계 문자열로 변환 이진 데이터 배열에서 바운더리 문자열로 변환 된 바이너리로 구분 된 각 본문 부분을 검색하고 각 페이로드에 대한 헤더를 추출하여 문자열로 변환 하시겠습니까? 또는
  2. 본문을 문자열 (집합 XMLHttpRequest.responseType = "text")로 취급하고 boundary-string으로 구분 된 본문 부분을 식별하고 페이로드를 이진 데이터 배열로 변환 하시겠습니까?

응답에 javascript/typescript에서 이러한 응답을 처리/분석하는 적절한 방법은 각각 자체 헤더 (문자열) 및 페이로드 (이진)가있는 본문 부분이 여러 개 포함되어 있기 때문에 무엇입니까?

더 간단한 방법이 있습니까?

모든 의견을 환영합니다. 감사!

답변

2

나는 당신이 "arraybuffer" 응답 유형을 사용하여 할 거라고하는 방법도 모르겠지만, 다중 구문 분석하기 전에이 사용했습니다는/응답의 byteranges :

function parseMultipartBody (body, boundary) { 
    return body.split(`--${boundary}`).reduce((parts, part) => { 
    if (part && part !== '--') { 
     const [ head, body ] = part.trim().split(/\r\n\r\n/g) 
     parts.push({ 
     body: body, 
     headers: head.split(/\r\n/g).reduce((headers, header) => { 
      const [ key, value ] = header.split(/:\s+/) 
      headers[key.toLowerCase()] = value 
      return headers 
     }, {}) 
     }) 
    } 
    return parts 
    }, []) 
} 

을하고 XMLHttpRequest를 함께 사용 아마 다음과 같이 보일 것입니다 :

const client = new XMLHttpRequest() 
client.open('GET', 'example.pdf', true) 
client.setRequestHeader('Range', 'bytes=500-999,7000-7999') 
client.onreadystatechange = function() { 
    if (client.readyState == 4 && client.status === 206) { 
    const boundary = client.getResponseHeader('Content-Type').match(/boundary=(.+)$/i)[1] 
    if (boundary) console.log('PARTS', parseMultipartBody(client.resposeText, boundary)) 
    } 
} 
client.send() 

귀하의 예제 응답의 출력은 다음과 같이 보일 것이다 :

[ 
    { 
    "body": "...the first range...", 
    "headers": { 
     "content-type": "application/pdf", 
     "content-range": "bytes 500-999/8000" 
    } 
    }, 
    { 
    "body": "...the second range", 
    "headers": { 
     "content-type": "application/pdf", 
     "content-range": "bytes 7000-7999/8000" 
    } 
    } 
] 
,