代码改变世界

idhttp+tidmultpartfromdatastream

2020-06-22 08:42  su_hq  阅读(317)  评论(0编辑  收藏  举报

参阅:https://www.cnblogs.com/ClaireWu/p/12487028.html

 

function xxx.UploadFile(const sAccessToken, sFile, sFileType: string):string;

var
  IdHttp: TIdHTTP;
  MutPartForm: TIdMultiPartFormDataStream;
  Ms: TStringStream;
  sTmp: string;
  LStream: TIdReadFileExclusiveStream;
  SSLIO: TIdSSLIOHandlerSocketOpenSSL;
begin
  Result := '';
  try
    Ms := TStringStream.Create('', TEncoding.UTF8);
    IdHttp := TIdHttp.Create(nil);
    IdHttp.ReadTimeout := 30000;
    MutPartForm := TIdMultiPartFormDataStream.Create;
    LStream := TIdReadFileExclusiveStream.Create(sFile);
    SSLIO := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
    try
      IdHttp.AllowCookies    := True;
      IdHttp.HandleRedirects := True//允许重定向
      SSLIO.SSLOptions.Method:=sslvTLSv1;
      SSLIO.SSLOptions.Mode := sslmClient;
      IdHttp.IOHandler := SSLIO;
      // Http1.1
      IdHttp.HTTPOptions := IdHttp.HTTPOptions + [hoKeepOrigProtocol];
      IdHttp.ProtocolVersion := pv1_1;
      MutPartForm.AddObject('media''application/octet-stream', LStream, ExtractFileName(sFile));
      sTmp := Format('http://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s',[sAccessToken, sFileType]);
      IdHttp.Post(sTmp, MutPartForm, Ms);
      Result := Ms.DataString;
    finally
      LStream.Free;
      Ms.Free;
      IdHttp.Free;
      MutPartForm.Free;
      SSLIO.Free;
    end;
  except
    on E: Exception do Result := E.Message;
  end;
end;