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;
    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
  rtcInfo;

procedure TfrmMain.Button1Click(Sender: TObject);
var
  cHttp: TNetHTTPClient;
  vData: TMultipartFormData;
  vRsp: TStringStream;
  i: Integer;
  sAppID, sAppSecret, sAccess_token: String;
  vR: TRtcValue;
begin
  // 以下是我的测试公众号信息，请修改成自己的测试公众号或者正式公众号
  sAppID := 'wx2c527055e2bb7c96';
  sAppSecret := 'a725be8fe6eab701888a8b4ef3cc839d';

  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('file', 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 := 'application/json; charset=utf-8;';
            UserAgent := 'Embarcadero URI Client/1.0';
            try
              Memo1.Lines.Add('获取access_token中...');
              Get('https://api.weixin.qq.com/cgi-bin/token?grant_type='
                + 'client_credential&appid=' + sAppID + '&secret='
                + sAppSecret, 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;
            vR := TRtcValue.Create;
            try
              vR.asRecord := TRtcRecord.FromJSON(vRsp.DataString);
              sAccess_token := vR.asRecord.asText['access_token'];
            finally
              vR.Free;
            end;
          end;
          vRsp.Clear;
          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('https://api.weixin.qq.com/cgi-bin/media/uploadimg?'
                + 'access_token=' + sAccess_token, 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.
