首页 > 代码库 > MFC之HTTP文件上传
MFC之HTTP文件上传
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")); DWORD 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); pHttpFile = 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); pHttpFile->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); DWORD sendLength = strPostData.GetLength() + endPostData.GetLength() + file.GetLength(); pHttpFile->SendRequestEx(sendLength, HSR_SYNC | HSR_INITIATE); pHttpFile->Write((LPSTR)(LPCTSTR)strPostData, strPostData.GetLength()); dwReadLength = -1; while (0 != dwReadLength) { dwReadLength = file.Read(pBuffer, dwChunkLength); if (dwReadLength > 0) { pHttpFile->Write(pBuffer, dwReadLength); } } file.Close(); pHttpFile->Write((LPSTR)(LPCTSTR)endPostData, endPostData.GetLength()); pHttpFile->EndRequest(); DWORD 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]; pEx->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(); pHttpFile = NULL; } if (connection != NULL) { connection->Close(); connection = NULL; } session.Close(); return bSuccess; }
MFC之HTTP文件上传
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。