WinInet類比HTTP POST上傳二進位檔案流

來源:互聯網
上載者:User
BOOL CDllValidateDlg::PostHttpPage(CString &result,CString &PageName,CString &postData) // 請求Http.{CInternetSession session("SighAgent");try{INTERNET_PORT nPort = 80;DWORD dwRet = 0;/*以下為wininet 網路請求流程*/CHttpConnection* pServer = session.GetHttpConnection(SERVER_IP, nPort);CHttpFile* pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST,PageName); //開啟一個請求CString strHeaders = "Content-Type: application/x-www-form-urlencoded"; // 要求標頭//開始發送請求string data_post = MultiByteToUtf8(postData.GetBuffer(0));pFile->SendRequest(strHeaders,(LPVOID)data_post.data(),data_post.size()); //發送請求,注意此為堵塞函數pFile->QueryInfoStatusCode(dwRet); //發送請求後,就查詢發送的結果if (dwRet == HTTP_STATUS_OK) //這個代表請求正確{CString str;while(pFile->ReadString(str)) //開始返回返回結果 {char *pStr = (char*)str.GetBuffer(str.GetLength()); //取得str對象的原始字串 result = result + str; }result = Utf8ToMultiByte(result.GetBuffer(0)).c_str();}else{SAFE_DELETE(pFile);SAFE_DELETE(pServer);return FALSE;}SAFE_DELETE(pFile);SAFE_DELETE(pServer);}catch (CInternetException* pEx){//catch errors from WinInetTCHAR pszError[200];pEx->GetErrorMessage(pszError, 200);OutputDebugString(pszError);return FALSE;}session.Close();return TRUE;}

我在程式裡用到上面這個PostHttpPage函數,來和伺服器互動資料。
之前的一些資料上傳都是字串或整型數,沒出現過問題。
現在想用這同一個函數,上傳二進位形式的檔案流,沒有成功。請問我下面的做法是哪裡錯了?
//二進位匯入圖片檔案char buffer[102400];  //BUF_SIZE大小自己定義FILE * pFile = fopen("photo.bmp", "rb");int img = fread(buffer, sizeof(char), 102400, pFile);//char stzimg[100];//itoa(img,stzimg,10);//AfxMessageBox(stzimg);//二進位匯入圖片檔案結束CString post_data;post_data.Format("matchid='%s'&matchname='%s'&aid='%d'&ticket='%d'""&name='%s'&gender='%d'&folk='%s'&birthday='%s'&addr='%s'&cardid='%s'&expire='%s'&agency='%s'&face='%s'",matchID,matchName,AID,ticket,Name,abs(stricmp(Gender,"女")),Folk,BirthDay,Address,Code, ExpireEnd,   Agency,buffer); //請求的附加參數CString result; //返回的結果CString post_page = "test_id_validater/update_num.php"; //請求的phpPostHttpPage(result,post_page,post_data);


回複討論(解決方案)

二進位考慮用BASE64編碼等,然後Post

你確定html協議是這樣傳二進位檔案的嗎,先用wireshark查看下

我在網上找到上傳檔案的代碼是這個樣子的:

  #include   #include   #include   #define ERROR_OPEN_FILE       10  #define ERROR_MEMORY          11  #define ERROR_SIZE            12  #define ERROR_INTERNET_OPEN   13  #define ERROR_INTERNET_CONN   14  #define ERROR_INTERNET_REQ    15  #define ERROR_INTERNET_SEND   16  using namespace std;  int main()  {     // Local variables     static char *filename   = "test.txt";   //Filename to be loaded     static char *type       = "image/jpg";     static char boundary[]  = "pippo";            //Header boundary     static char nameForm[]  = "uploadedfile";     //Input form name     static char iaddr[]     = "localhost";        //IP address     static char url[]       = "test.php";         //URL     char hdrs[255];                  //Headers     char * buffer;                   //Buffer containing file + headers     char * content;                  //Buffer containing file     FILE * pFile;                    //File pointer     long lSize;                      //File size     size_t result;                        // Open file     pFile = fopen ( filename , "rb" );     if (pFile==NULL) return ERROR_OPEN_FILE;     // obtain file size:     fseek (pFile , 0 , SEEK_END);     lSize = ftell (pFile);     rewind (pFile);     // allocate memory to contain the whole file:     content = (char*) malloc (sizeof(char)*lSize);     if (content == NULL) return ERROR_MEMORY;     // copy the file into the buffer:     result = fread (content,1,lSize,pFile);     if (result != lSize) return ERROR_SIZE;     // terminate     fclose (pFile);     //allocate memory to contain the whole file + HEADER     buffer = (char*) malloc (sizeof(char)*lSize + 2048);     //print header     sprintf(hdrs,"Content-Type: multipart/form-data; boundary=%s",boundary);     sprintf(buffer,"--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n",boundary,nameForm,filename);     sprintf(buffer,"%sContent-Type: %s\r\n\r\n",buffer,type);     sprintf(buffer,"%s%s\r\n",buffer,content);     sprintf(buffer,"%s--%s--\r\n",buffer,boundary);     //Open internet connection     HINTERNET hSession = InternetOpen("WinSock",INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);     if(hSession==NULL) return ERROR_INTERNET_OPEN;     HINTERNET hConnect = InternetConnect(hSession, iaddr,INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);     if(hConnect==NULL) return ERROR_INTERNET_CONN;     HINTERNET hRequest = HttpOpenRequest(hConnect, (const char*)"POST",url, NULL, NULL, (const char**)"*/*\0", 0, 1);     if(hRequest==NULL) return ERROR_INTERNET_REQ;     BOOL sent= HttpSendRequest(hRequest, hdrs, strlen(hdrs), buffer, strlen(buffer));     if(!sent) return ERROR_INTERNET_SEND;     //close any valid internet-handles     InternetCloseHandle(hSession);     InternetCloseHandle(hConnect);     InternetCloseHandle(hRequest);     return 0;  }

這應該是把檔案以二進位形式傳給test.php吧。那麼在test.php那邊怎麼接收這個二進位,並寫入mysql資料庫的某個欄位呢?

它可以和別的整型數及字串在同一次post中提交嗎?

這應該是把檔案以二進位形式傳給test.php吧。那麼在test.php那邊怎麼接收這個二進位,並寫入mysql資料庫的某個欄位呢?


要看對應的php是如何處理的。然後你發送對應格式的資料


這應該是把檔案以二進位形式傳給test.php吧。那麼在test.php那邊怎麼接收這個二進位,並寫入mysql資料庫的某個欄位呢?


要看對應的php是如何處理的。然後你發送對應格式的資料



對應PHP檔案是用$bian_liang_ming = $_REQUEST['xxxx'];
來擷取傳過去的參數的。這種情況如何傳遞位元據流啊?

你是玩C的,你應該清楚的知道字串是依靠尾部附加的 '\0' 來判斷結束的,那你如何能保證圖片資料中不出現'\0' 而導致字串提前結束呢?

你是玩C的,你應該清楚的知道字串是依靠尾部附加的 '\0' 來判斷結束的,那你如何能保證圖片資料中不出現'\0' 而導致字串提前結束呢?


我其實並不知道確切該怎麼做,所以隨便套用了之前傳遞整型數的辦法,知道是不對的。

c++ 應用 curl 庫函數實現,這樣少了協議的處理,事情變得單純了
也可以用 sock 庫函數實現
你 #3 的代碼就是 sock 應用的一個例子

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.