TsgcWebSocketServer_HTTPAPI | Send File Response

HTTP 요청에 대한 응답으로 파일을 보내려면 THttpServerResponse 객체의 FileName 속성을 사용하십시오.

 


void __fastcall OnHTTPRequest(TsgcWSConnection_HTTPAPI *aConnection,
	const THttpServerRequest *aRequestInfo,
	THttpServerResponse *aResponseInfo)
{
  if (aRequestInfo->Method == "GET")
  {
    if (aRequestInfo->Document == "/test.zip")
	{
	  aResponseInfo->ResponseNo = 200;
	  aResponseInfo->FileName = "c:\download\test.zip";
	  aResponseInfo->ContentType = "application/zip";
	}
	else
	{
	  aResponseInfo->ResponseNo = 404;
	}
  }
  else
  {  
    aResponseInfo->ResponseNo = 500;
  }
}

Resumable Downloads

HTTP 206 Partial Content 응답은 전체 파일을 보내는 대신 서버가 리소스의 특정 부분(범위)에 대한 요청을 이행할 때 사용됩니다. 이는 일반적으로 재개 가능한 다운로드, 미디어 스트리밍, 대용량 파일 전송에 사용됩니다.

작동 방식:

 

클라이언트가 부분 리소스를 요청함: 클라이언트(브라우저, 다운로더 또는 미디어 플레이어)는 원하는 바이트 범위를 지정하는 Range 헤더를 보냅니다. 요청 예:

 

GET /video.mp4 HTTP/1.1
Host: example.com
Range: bytes=1000-5000

 

이것은 video.mp4의 1000~5000 바이트를 요청합니다.

 

서버가 HTTP 206으로 응답: 서버가 범위 요청을 지원하면 206 Partial Content로 응답하고 Content-Range 헤더를 포함합니다. 예제 응답:

 

HTTP/1.1 206 Partial Content
Content-Range: bytes 1000-5000/1000000
Content-Length: 4001
Content-Type: video/mp4

 

Content-Range 헤더는 다음을 보여줍니다:

 

제공되는 범위(1000-5000)

파일의 총 크기(1000000바이트)입니다.

Content-Length 헤더는 반환된 부분의 크기입니다(4001바이트).

 

Client Can Request More Chunks:

클라이언트는 서로 다른 부분에 대해 여러 요청을 보낼 수 있습니다.

이는 재개 가능한 다운로드와 효율적인 스트리밍을 가능하게 합니다.

 


void __fastcall OnHTTPRequest(TIdContext* AContext, TIdHTTPRequestInfo* ARequestInfo, TIdHTTPResponseInfo* AResponseInfo)
{
    std::unique_ptr<TFileStream> oStream(new TFileStream("test.pdf", fmOpenRead | fmShareDenyWrite));
    std::unique_ptr<TIdEntityRangeStrings> oRanges(new TIdEntityRangeStrings(nullptr));
    try {
        oRanges->Text = ARequestInfo->RawHeaders->Values["Range"];
        AResponseInfo->ContentType = "application/pdf";
        if (oRanges->Count > 0) {
            AResponseInfo->ResponseNo = 206; // Partial Content
            AResponseInfo->AcceptRanges = "bytes";
            AResponseInfo->ContentRangeStart = oRanges->Items[0]->StartPos;
            AResponseInfo->ContentRangeEnd = oRanges->Items[0]->EndPos;
            AResponseInfo->ContentRangeInstanceLength = oStream->Size;
            
            AResponseInfo->ContentStream = new TIdHTTPRangeStream(oStream.release(), 
                AResponseInfo->ContentRangeStart, AResponseInfo->ContentRangeEnd);
        } else {
            AResponseInfo->ResponseNo = 200; // OK
            AResponseInfo->ContentStream = oStream.release();
        }
    } catch (...) {
        // Handle exceptions
    }
}