最近工作需要對接企業微信的推送信息接口
里面有發文件的功能
所以特地記錄下上傳文件並且使用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)