Utilizzare la proprietà FileName dell'oggetto THttpServerResponse se si desidera inviare un file come risposta a una richiesta HTTP.
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;
Una risposta HTTP 206 Partial Content viene utilizzata quando un server soddisfa una richiesta per una porzione specifica (intervallo) di una risorsa, invece di inviare l'intero file. Questo è comunemente usato per download ripristinabili, streaming multimediale e trasferimenti di file di grandi dimensioni.
Come funziona:
Il client richiede una risorsa parziale: Il client (browser, downloader o media player) invia un'intestazione Range che specifica l'intervallo di byte desiderato. Esempio di richiesta:
GET /video.mp4 HTTP/1.1
Host: example.com
Range: bytes=1000-5000
Questo richiede i byte da 1000 a 5000 di video.mp4.
Il server risponde con HTTP 206: Se il server supporta le richieste di intervallo, risponde con 206 Partial Content e include un'intestazione Content-Range. Esempio di risposta:
HTTP/1.1 206 Partial Content
Content-Range: bytes 1000-5000/1000000
Content-Length: 4001
Content-Type: video/mp4
L'intestazione Content-Range mostra:
L'intervallo servito (1000-5000)
La dimensione totale del file (1000000 byte).
L'intestazione Content-Length è la dimensione della porzione restituita (4001 byte).
Il Client può richiedere altri chunk:
Il client può inviare più richieste per parti diverse.
Questo consente download riprendibili e streaming efficiente.
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;