BOOL Uploadrecfile (lpctstr strurl, LPCTSTR strlocalfilename) {if (strURL = = NULL | | strURL = = _t ("") | | Strlocalfilename = = NULL | | Strlocalfilename = = _t ("") | |! PathFileExists (strlocalfilename) | | Pathisdirectory (Strlocalfilename)) {return FALSE;} CHttpFile *phttpfile = NULL; chttpconnection* connection = NULL; CInternetSession session (_t ("UploadFile"));D word dwtype;internet_port nport; CString strserver, Strobject;if (! AfxParseURL (strURL, dwtype, strserver, Strobject, Nport)) return FALSE; BOOL bsuccess = False;dword dwreadlength;dword dwresponselength;dword dwtotalrequestlength;const DWORD dwChunkLength = 1024;char Pbuffer[dwchunklength];memset (pbuffer, 0, dwchunklength); try{connection = Session. GetHttpConnection (strserver, nport);p httpfile = Connection->openrequest (Chttpconnection::http_verb_post, Strobject); CTime CT; CString strtime, strboundary;ct = Ctime::getcurrenttime (); strtime = Ct. Format (_t ("%y%m%d%h%m%s")), strboundary = _t ("*-*-*") + Strtime + _t ("*-*-*"); CString Strprefileheaders;sTrprefileheaders.format (_t ("Content-type:multipart/form-data; Boundary=%s\r\n "), strboundary);p httpfile->addrequestheaders (strprefileheaders); CString Strpostdata;strpostdata.format (_t ("--%s\r\ncontent-disposition:form-data; Name =\ "Voice\"; Filename=\ "%s.wav\" \r\ncontent-type:audio/x-wav\r\n\r\n "), Strboundary, strtime); CString Endpostdata;endpostdata.format (_t ("\r\n--%s--\r\n"), strboundary); CFile File;file. Open (Strlocalfilename, Cfile::sharedenynone | Cfile::moderead);D Word sendlength = strpostdata.getlength () + endpostdata.getlength () + file. GetLength ();p Httpfile->sendrequestex (sendlength, Hsr_sync | hsr_initiate);p Httpfile->write ((LPSTR) (LPCTSTR) Strpostdata, Strpostdata.getlength ());d wreadlength = -1;while (0 ! = dwreadlength) {dwreadlength = file. Read (pbuffer, dwchunklength); if (Dwreadlength > 0) {phttpfile->write (pbuffer, dwreadlength);}} File. Close ();p httpfile->write ((LPSTR) (LPCTSTR) Endpostdata, Endpostdata.getlength ());p httpfile->endrequest ();D WORD dwstauts;if (!phttpfile->queryinfostatuscode (dwstauts) | | Dwstauts < 200 | | 299 < dwstauts) {bsuccess = FALSE;} Else{cstring response, text;for (int i = 0; phttpfile->readstring (text); ++i) {response + = text + "\ r \ n";} bsuccess = TRUE;}} catch (CInternetException * pEx) {char sz[256];p ex->geterrormessage (SZ, 25); CString Str;str. Format ("Internetexception occur:%s", SZ); if (Pmaindlg) {pmaindlg->outputlogline (str);} bsuccess = FALSE;} catch (...) {bsuccess = FALSE;} if (phttpfile! = null) {phttpfile->close ();p httpfile = null;} if (connection! = null) {connection->close (); connection = null;} Session. Close (); return bsuccess;}
MFC HTTP File Upload