CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2021
    Posts
    2

    Exclamation Winhttp Does Not Post File

    I have combed all over here for similar questions and have done all suggestions but for some weird reason my code doesn't upload the file to the server.

    C++ code

    Code:
    PCHAR sendWebRequest(LPWSTR szServerNameOrIP, LPWSTR szVerb, LPWSTR szServerPath, PCHAR szFileToPost)
    {
     HINTERNET hSession;
     HINTERNET hConnect;
     HINTERNET hRequest;
    
     BOOL bResults = FALSE;
    
     LPCWSTR szUserAgent = L"MyCustomUserAgent";
    
     DWORD dwSize, dwDownloaded;
     PCHAR szTempRespBuff;
     PCHAR szRawResponse = (PCHAR)malloc(MAX_PATH); 
    
     strcpy_s(szRawResponse, MAX_PATH, "");
    
     int nBuffSize;
    
    try{
    
        // Use WinHttpOpen to obtain a session handle.
        hSession = WinHttpOpen(szUserAgent, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
        if (hSession == NULL)
        {
            //printf("[x] Could not create session!\n");
            MessageBox(0, L"WinOpenError", L"", 0);
            throw(0);
        }
    
        // Specify an HTTP server.
        hConnect = WinHttpConnect(hSession, szServerNameOrIP, INTERNET_DEFAULT_HTTP_PORT, 0);
        if (hConnect == NULL)
        {
            //printf("[x] Could not connect to the host!\n");
            MessageBox(0, L"WinConnectError", L"", 0);
            throw(0);
        }
    
        // Create an HTTP request handle.
        hRequest = WinHttpOpenRequest(hConnect, szVerb, szServerPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_REFRESH);
        if (hRequest == NULL)
        {
            //printf("[x] Failed to get request handle!\n");
            MessageBox(0, L"WinOpenRequestError", L"", 0);
            throw(0);
        }
    
        // Add request headers.
        bResults = WinHttpAddRequestHeaders(hRequest, 
                                            L"Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryaUZw4AF9WYYzUrpM",
                                            -1L, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE);
    
        if (!bResults)
        {
            MessageBox(0, L"WinHttpAddRequestHeadersError", L"", 0);
            throw(0);
        }
    
        CHAR szPostData0[440],
             szPostData1[60],
             szPostTemp[120];
    
        ZeroMemory(szPostData0, sizeof(szPostData0));
        ZeroMemory(szPostData1, sizeof(szPostData1));
        ZeroMemory(szPostTemp, sizeof(szPostTemp));
    
    
        strcpy_s(szPostData0, 440, "------WebKitFormBoundaryaUZw4AF9WYYzUrpM\r\n");
    
        PCHAR fileName  = PathFindFileNameA(szFileToPost);
        wsprintfA(szPostTemp, "Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"%s\"\r\n", fileName);
        strcat_s(szPostData0, 440, szPostTemp);
    
        strcat_s(szPostData0, 440, "Content-Type: text/plain\r\n\r\n");
    
        strcpy_s(szPostData1, 60, "\r\n------WebKitFormBoundarygQFYVyK9cnuuaQYb--\r\n");
    
         // Open the existing file.
        HANDLE hFile = CreateFileA(szFileToPost, GENERIC_READ, 0, NULL,
                             OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    
        if (hFile == INVALID_HANDLE_VALUE)
        {
            MessageBox(0, L"CreateFileAError", L"", 0);
            throw(0);
        }
    
        //Make sure size is not more than 300kb
        size_t fileSize = GetFileSize(hFile, NULL);
        if (fileSize > 307200)
        {
            MessageBox(0, L"FileSize too large!", L"", 0);
            throw(0);
        }
    
    
        //Send Request
        int lenBytes = strlen(szPostData0 + 1) + strlen(szPostData1 + 1) + fileSize;
    
        bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS , 0, WINHTTP_NO_REQUEST_DATA, 0, lenBytes, NULL);
        if (!bResults)
        {
            //printf("[x] Failed to send request!\n");
            int error = GetLastError();
    
            TCHAR szbuff[25];
            wsprintf(szbuff, L"Error %d", error);
            MessageBox(0, L"WinSendRequestError", szbuff, 0);
            throw(0);
        }
    
        //Write First Post Data
        DWORD numberOfBytesRead, numberOfBytesWritten;
        WinHttpWriteData(hRequest, szPostData0, (DWORD)strlen(szPostData0+1), &numberOfBytesWritten);
    
        //Write File Buffer
        PCHAR fileBytes = (PCHAR)malloc(fileSize);
        ReadFile(hFile, fileBytes, fileSize, &numberOfBytesRead, NULL);
        WinHttpWriteData(hRequest, fileBytes, fileSize, &numberOfBytesWritten);
    
        
        //Write Last Post Data
        WinHttpWriteData(hRequest, szPostData1, (DWORD)strlen(szPostData1+1), &numberOfBytesWritten);
    
    
        //Receive the response
        bResults = WinHttpReceiveResponse(hRequest, NULL);
        if (!bResults)
        {
            int err = GetLastError();
                wsprintfA(szPostTemp, "WinHttpReceiveResponseError %d", err);
    
                MessageBoxA(0, szPostTemp, "", 0);
            throw(0);
        }
    
        //Read Response Received
    
        do {
    
            // Check for available data.
            dwSize = 0;
            if( !WinHttpQueryDataAvailable(hRequest, &dwSize) )
            {
                //printf( "Error %u in WinHttpQueryDataAvailable.\n", GetLastError() );
                MessageBox(0, L"WinHttpQueryDataAvailableError", L"", 0);
                throw(0);
            }
    
            // Allocate space for the buffer.
            nBuffSize = (dwSize+1);
            szTempRespBuff = (PCHAR)malloc(nBuffSize);
    
            if (szTempRespBuff == NULL)
            {
                //printf( "Error allocation space for response");
                throw(0);
            }
    
            // Read the data.
            ZeroMemory(szTempRespBuff, nBuffSize);
    
            if(WinHttpReadData( hRequest, (LPVOID)szTempRespBuff, dwSize, &dwDownloaded ))
                strcat_s(szRawResponse, MAX_PATH, szTempRespBuff);
    
            // Free the memory allocated to the buffer.
            free(szTempRespBuff);
    
        }while (dwSize > 0);
    
    
        //Close Handles
        WinHttpCloseHandle(hSession);
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hRequest);
    
        return szRawResponse;
    
    }catch(...)
    {
        if(hSession)
            WinHttpCloseHandle(hSession);
    
        if(hConnect)
            WinHttpCloseHandle(hConnect);
    
        if(hRequest)
            WinHttpCloseHandle(hRequest);
    }
    
    
      return "WINHTTP_ERROR";
    
    }
    
      int main()
    {
        PCHAR response = sendWebRequest(L"127.0.0.1", L"POST", L"/panel/ups.php", "hello.txt");
    
        MessageBoxA(0, response, "", 0);
    
        return 0;
    }

    And PHP Code

    PHP Code:
    <?php
       
    if(isset($_FILES['fileToUpload'])){
          
    $errors= array();
          
    $file_name $_FILES['fileToUpload']['name'];
          
    $file_size =$_FILES['fileToUpload']['size'];
          
    $file_tmp =$_FILES['fileToUpload']['tmp_name'];
          
    $file_type=$_FILES['fileToUpload']['type'];
          
    $file_ext explode('.',$_FILES['fileToUpload']['name']);
          
    $file_ext=strtolower(end($file_ext));
          
          
    $extensions= array("jpeg","jpg","png""txt");
          
          if(
    in_array($file_ext,$extensions)=== false){
             
    $errors[]="extension not allowed, please choose a JPEG or PNG file or Txt";
          }
          
          if(
    $file_size 1048576){
             
    $errors[]='File size must not exceed 1 MB';
          }
          
          if(empty(
    $errors)==true){
             
    move_uploaded_file($file_tmp,"images/".$file_name);
             echo 
    "success";
          }else{
             
    print_r($errors);
          }
       }
    ?>
    <html>
       <body>
          
          <form action="" method="POST" enctype="multipart/form-data">
             <input type="file" name="fileToUpload" />
             <input type="submit"/>
          </form>
          
       </body>
    </html>


    I have used wireshark and everything but still. Manual upload in browser works but not using c code. What am i doing wrong?

  2. #2
    Join Date
    May 2001
    Location
    Germany
    Posts
    1,158

    Re: Winhttp Does Not Post File

    Since you are doing error checking, you should be able to tell where the code fails and you should also be able to get the error using GetLastError. That would at least be a starting point.

  3. #3
    Join Date
    Dec 2021
    Posts
    2

    Re: Winhttp Does Not Post File

    I fixed it . I shortened the boundary and it worked . I donít know why but it seems to work 🙏

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured