最近工作需要对接企业微信的推送信息接口
里面有发文件的功能
所以特地记录下上传文件并且使用idhttp遇到的访问ssl网址报错问题
参考文档:https://blog.csdn.net/huohuotu/article/details/77337087
官方上传临时素材文档:https://work.weixin.qq.com/api/doc/90000/90135/90253
下面不多说,直接贴上代码
function xxx.UploadFile(const sAccessToken, sFile, sFileType: string):string; var IdHttp: TIdHTTP; MutPartForm: TIdMultiPartFormDataStream; Ms: TStringStream; sTmp: string; begin Result := ''; try Ms := TStringStream.Create('', TEncoding.UTF8); IdHttp := TIdHttp.Create(nil); IdHttp.ReadTimeout := 30000; MutPartForm := TIdMultiPartFormDataStream.Create; try IdHttp.AllowCookies := True; IdHttp.HandleRedirects := True; //允许重定向 // Http1.1 IdHttp.HTTPOptions := IdHttp.HTTPOptions + [hoKeepOrigProtocol]; IdHttp.ProtocolVersion := pv1_1; //MutPartForm.AddFormField('file', 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 Ms.Free; IdHttp.Free; MutPartForm.Free; end; except on E: Exception do Result := E.Message; end; end;
但是这段代码会遇到两个问题:
1:发送的文件显示了完整的路径和文件名
2:有时候会报 IOHandler value is not valid错误
当然,如果你不在意文件名并且没有遇到这个报错问题的话,可以用这段代码
下面是解决这两个问题的改进版:
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;
需要增加uses引用的单元:IdGlobal, IdHTTP, IdMultipartFormData, IdSSLOpenSSL
三个参数 ,获取的access_token, 文件路径,和文件类型,
文件类型:分别有图片(image)、语音(voice)、视频(video),普通文件(file)