如果您想将文件作为 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 部分内容响应。这通常用于可续传的下载、媒体流传输和大文件传输。
工作原理:
客户端请求部分资源:客户端(浏览器、下载器或媒体播放器)发送一个指定所需字节范围的 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;