IdHTTPServer服务接收文件

procedure TForm1.IdHTTPServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
  FileStream: TFileStream;
begin
  if ARequestInfo.PostStream <> nil then
  begin
    ARequestInfo.PostStream.Position := 0;
    FileStream := TFileStream.Create('1.jpg', fmCreate);
    FileStream.CopyFrom(ARequestInfo.PostStream, ARequestInfo.PostStream.Size); { Copy 流 }
    FileStream.Free;
  end;
end;

 

Delphi 是一种常用的编程语言,我们可以使用 Delphi 编写一个简单的 HTTP 文件服务器。首先,我们需要设置一个端口用于文件服务器的监听,通常 HTTP 的默认端口为 80,但是可能被其他应用程序占用,因此我们可以选择一个未被占用的端口(例如 8080),接下来,我们需要编写代码启动文件服务器。以下是示例代码: ``` uses IdHTTPServer, IdCustomHTTPServer, IdGlobal, IdContext, System.Classes; type TMyServer = class(TIdHTTPServer) protected procedure DoCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); override; end; var MyServer: TMyServer; procedure TMyServer.DoCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var FileName: string; begin inherited; FileName := ExtractFileName(ARequestInfo.Document); // set the content type based on the file extension if SameText(ExtractFileExt(FileName), '.html') then AResponseInfo.ContentType := 'text/html' else if SameText(ExtractFileExt(FileName), '.css') then AResponseInfo.ContentType := 'text/css' else if SameText(ExtractFileExt(FileName), '.js') then AResponseInfo.ContentType := 'application/javascript' else AResponseInfo.ContentType := 'text/plain'; AResponseInfo.ContentStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); end; begin MyServer := TMyServer.Create(nil); try MyServer.DefaultPort := 8080; MyServer.Active := True; WriteLn('Server is running...'); ReadLn; finally MyServer.Free; end; end. ``` 在这个示例中,我们定义了一个名为 TMyServer 的类,并在其中实现了 DoCommandGet 方法来处理 HTTP GET 请求。我们根据请求的文件类型设置 Content-Type,并使用 TFileStream 加载该文件的内容并发送给客户端。在主函数中,我们创建了一个 TMyServer 对象并设置默认端口为 8080,然后启动该服务器并等待用户输入来停止服务器。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值