1. 程式人生 > >MFC通過Http請求上傳檔案

MFC通過Http請求上傳檔案

FMC通過Http請求上傳檔案

void CMFCApplication1Dlg::HttpPostFile(string url, CString file, string paramName, string contentType)
{

    CInternetSession pSession(_T("ic_PostWav"));  //可以隨意
    CHttpConnection* pConnect;
    CHttpFile *       pFile;

    //通過  url解析出來 
    CString pServeIP = _T("127.0.0.1");
    INTERNET_PORT wPort = 8888
; CString pObject = _T("/api/v1/documents/upload"); pConnect = pSession.GetHttpConnection(pServeIP, wPort); pFile = pConnect->OpenRequest(CHttpConnection::HTTP_VERB_POST, pObject, NULL, 0, NULL, NULL, INTERNET_FLAG_DONT_CACHE); string boundary = "----1a2b3c4d5e6f"; //Http 頭部 string
pPostHeader; pPostHeader = "Accept:audio/x-wav,text/html,application/xhtml+xml,application/xml,*/*;q=0.9,*/*;q=0.8\r\n"; pPostHeader += "Content-Type: multipart/form-data;"; pPostHeader += "boundary=" + boundary + "\r\n"; pPostHeader += "Connection: keep-alive\r\n"; CString httpHead; httpHead.Format(_T("%s"
), pPostHeader); pFile->AddRequestHeaders(httpHead); //資料幀頭 string dataTop, name,filename; name = "name"; filename = "filename"; dataTop = "--"+ boundary +"\r\n"; dataTop += "Content-Disposition:form-data;"; dataTop += "name=\"" + name + "\";"; dataTop += "filename=\"" + filename + "\"\r\n"; dataTop += "Content-Type:" + contentType + "\r\n\r\n"; //byte* pPostTopbytes = new byte[dataTop.length()]; //todo //for (int i = 0; i < dataTop.length();i++) //{ // pPostTopbytes[i] = (byte)dataTop[i]; //} byte* pPostTopbytes = (byte*)dataTop.c_str(); //資料包尾 string dataEnd; dataEnd = "\r\n--" + boundary + "--\r\n"; //byte* enderbyte = new byte[ dataEnd.size()]; //todo //for (int i = 0; i < dataEnd.length(); i++) //{ // enderbyte[i] = (byte)dataEnd[i]; //} byte* enderbyte = (byte*)dataEnd.c_str(); CFile cfile; cfile.Open(file, CFile::modeRead | CFile::shareDenyRead, NULL); DWORD dwSize = dataTop.length() + dataEnd.length() + cfile.GetLength(); pFile->SendRequestEx(dwSize); //寫資料頭 pFile->Write(pPostTopbytes, dataTop.length()); //寫資料主體 int bufflength = 4 * 1024; byte* buffer = new byte[bufflength]; int byteRead = 0; while ((byteRead = cfile.Read(buffer, bufflength)) != 0) { pFile->Write(buffer, byteRead); } cfile.Close(); //寫資料尾部 pFile->Write(enderbyte, dataEnd.length() ); //傳送檔案 pFile->EndRequest(); //接收返回 CString strSentence = _T(""), strGetSentence = _T(""); DWORD dwRet; pFile->QueryInfoStatusCode(dwRet); if (HTTP_STATUS_OK == dwRet) { while (pFile->ReadString(strSentence)) // 讀取提交資料後的返回結果 { strGetSentence = strGetSentence + strSentence; } char * temp = (char*)strGetSentence.GetBuffer(strGetSentence.GetLength()); string reponce(temp); //todo: 將返回的編碼資料轉為自己需要的編碼資料 } pFile->Close(); pConnect->Close(); } void CMFCApplication1Dlg::OnBnClickedOk() { //呼叫方式 HttpPostFile("", L"E:\\123\\內牆With柱fbx.pcx"/*L"E:\\123\\test.txt"*/, "uploadeFile", "application/octet-stream" /*L"text/plain"*/); }