unit frmMainUnit;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;

type
  TfrmMain = class(TForm)
    OpenDialog1: TOpenDialog;
    Button1: TButton;
    Memo1: TMemo;
    LabeledEdit1: TLabeledEdit;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  frmMain: TfrmMain;

implementation

{$R *.dfm}


uses System.Net.Mime, // 用于支持 TMultipartFormData
  System.Net.HttpClientComponent; // 用于支持 TNetHTTPClient

procedure TfrmMain.Button1Click(Sender: TObject);
var
  cHttp: TNetHTTPClient;
  vData: TMultipartFormData;
  vRsp: TStringStream;
  i: Integer;
begin
  { *
    因为接口只支持单文件接收，所以采用循环提交的形式处理，
    对于支持多文件的，只要AddFile多个文件就行。
    * }
  if OpenDialog1.Execute then
  begin
    cHttp := TNetHTTPClient.Create(nil);
    vRsp := TStringStream.Create('', TEncoding.GetEncoding(65001));
    try
      for i := 0 to OpenDialog1.Files.Count - 1 do
      begin
        vData := TMultipartFormData.Create;
        try
          vData.AddFile('fname', OpenDialog1.Files.Strings[i]);
          vData.AddField('utt', LabeledEdit1.Text);
          with cHttp do
          begin
            ConnectionTimeout := 2000; // 2秒
            ResponseTimeout := 10000; // 10秒
            AcceptCharSet := 'utf-8';
            AcceptEncoding := '65001';
            AcceptLanguage := 'zh-CN';
            ContentType := 'multipart/form-data';
            UserAgent := 'Embarcadero URI Client/1.0';
            try
              Memo1.Lines.Add('尝试上传文件 ' + OpenDialog1.Files.Strings[i]);
              Post('http://localhost:8833/upfile', vData, vRsp);
              Application.ProcessMessages;
            except
              on E: Exception do
                // Error sending data: (12002) 操作超时.
                // Error receiving data: (12002) 操作超时
                if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error sending data'
                then
                  Memo1.Lines.Add('Error:连接失败！')
                else if Copy(E.Message, 1, Pos(':', E.Message) - 1) = 'Error receiving data'
                then
                  Memo1.Lines.Add('Error:接收失败，请延长接收超时时间！')
                else
                  Memo1.Lines.Add('Error:' + E.Message);
            end;
            Memo1.Lines.Add(vRsp.DataString);
          end;
        finally
          vData.Free;
        end;
      end;
    finally
      cHttp.Free;
      vRsp.Free;
    end;
  end;
end;

end.
