WinInet simulates HTTPPOST to upload binary file streams

Source: Internet
Author: User
Tags integer numbers
WinInet simulates HTTPPOST to upload binary file streams
BOOL CDllValidateDlg: PostHttpPage (CString & result, CString & PageName, CString & postData) // request Http. {CInternetSession session ("SighAgent"); try {INTERNET_PORT nPort = 80; DWORD dwRet = 0;/* The following is the wininet network request process */CHttpConnection * pServer = session. getHttpConnection (SERVER_IP, nPort); CHttpFile * pFile = pServer-> OpenRequest (CHttpConnection: HTTP_VERB_POST, PageName); // open a request CString strHeaders = "Content-Type: application/x-www-form-urlencoded "; // request header // start sending the request string data_post = MultiByteToUtf8 (postData. getBuffer (0); pFile-> SendRequest (strHeaders, (LPVOID) data_post.data (), data_post.size (); // send a request, note that this is the blocking function pFile-> QueryInfoStatusCode (dwRet); // query the sent result if (dwRet = HTTP_STATUS_ OK) after the request is sent) // This indicates that the request is correct {CString str; while (pFile-> ReadString (str) // start to return the returned result {char * pStr = (char *) str. getBuffer (str. getLength (); // obtain the original string result of the str object = 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 ;}

I used the PostHttpPage function in the program to interact with the server.
Some of the previous data uploads are strings or integer numbers, so there is no problem.
Now I want to use the same function to upload a file stream in the binary format. What are the following mistakes?
// Binary import image FILE char buffer [102400]; // BUF_SIZE custom FILE * pFile = fopen ("photo.bmp", "rb"); int img = fread (buffer, sizeof (char), 102400, pFile); // char stzimg [100]; // itoa (img, stzimg, 10); // AfxMessageBox (stzimg ); // end of the binary import image file 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 ); // the request's additional parameter CString result; // The Returned result CString post_page = "test_id_validater/update_num.php"; // The requested phpPostHttpPage (result, post_page, post_data );


Reply to discussion (solution)

BASE64 encoding for binary data, and Post

Are you sure you want to use the html protocol to transfer binary files like this? check it with wireshark.

I found the code for uploading files on the Internet as follows:

  #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;  }
   
  
 

This should be to pass the file to test. php in binary format. So how does one receive this binary in test. php and write it into a field in the mysql database?

Can it be submitted in the same post as other integer numbers and strings?

This should be to pass the file to test. php in binary format. So how does one receive this binary in test. php and write it into a field in the mysql database?


It depends on how php works. Then you can send the data in the corresponding format.


This should be to pass the file to test. php in binary format. So how does one receive this binary in test. php and write it into a field in the mysql database?


It depends on how php works. Then you can send the data in the corresponding format.



The corresponding php file is $ bian_liang_ming =$ _ REQUEST ['xxxx'];
To obtain the passed parameters. In this case, how does one transmit binary data streams?

You are playing C. You should be clear that the string is determined by the '\ 0' appended to the tail, then, how can you ensure that the string ends ahead of schedule without '\ 0' in the image data?

You are playing C. You should be clear that the string is determined by the '\ 0' appended to the tail, then, how can you ensure that the string ends ahead of schedule without '\ 0' in the image data?


I don't know exactly how to do it, so I just applied the method of passing the integer number, and I knew it was wrong.

C ++ applies the curl library function implementation, which reduces the protocol processing and simplifies the process.
You can also use the sock library function.
Your #3 code is an example of a sock application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.