HTTP リクエストへの応答としてファイルを送信したい場合は、THttpServerResponse オブジェクトの FileName プロパティを使用してください。
procedure OnHTTPRequest(aConnection: TsgcWSConnection_HTTPAPI;
const aRequestInfo: THttpServerRequest;
var aResponseInfo: THttpServerResponse);
begin
if aRequestInfo.Method = 'GET' then
begin
if aRequestInfo.Document = '/test.zip' then
begin
aResponseInfo.ResponseNo := 200;
aResponseInfo.FileName := 'c:\download\test.zip';
aResponseInfo.ContentType := 'application/zip';
end
else
aResponseInfo.ResponseNo := 404;
end
else
aResponseInfo.ResponseNo := 500;
end;
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バイト)です。
クライアントはより多くのチャンクをリクエストできます:
クライアントは異なるパーツに対して複数のリクエストを送信できます。
これにより、再開可能なダウンロードと効率的なストリーミングが可能になります。
procedure OnHTTPRequest(aConnection: TsgcWSConnection_HTTPAPI;
const aRequestInfo: THttpServerRequest; var aResponseInfo: THttpServerResponse);
var
oStream: TFileStream;
oRanges: TIdEntityRanges;
begin
oStream := TFileStream.Create('test.pdf', fmOpenRead);
oRanges := TIdEntityRanges.Create(nil);
Try
oRanges.Text := aRequestInfo.Range;
aResponseInfo.ContentType := 'application/pdf';
if oRanges.Count > 0 then
begin
aResponseInfo.ResponseNo := 206;
aResponseInfo.AcceptRanges := 'bytes';
aResponseInfo.ContentRangeStart := oRanges[0].StartPos;
aResponseInfo.ContentRangeEnd := oRanges[0].EndPos;
aResponseInfo.ContentRangeInstanceLength := oStream.Size;
aResponseInfo.ContentStream := TIdHTTPRangeStream.Create(oStream,
aResponseInfo.ContentRangeStart, aResponseInfo.ContentRangeEnd);
end
else
begin
aResponseInfo.ResponseNo := 200;
aResponseInfo.ContentStream := oStream;
end;
Finally
oRanges.Free;
End;
end;