TheTherminator
TheTherminator

Reputation: 101

use POST to send a file using c++

#include <winsock2.h>
#include <windows.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main (){
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
        cout << "WSAStartup failed.\n";
        system("pause");
        return 1;
    }
    SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    struct hostent *host;
    host = gethostbyname("127.0.0.1");
    SOCKADDR_IN SockAddr;
    SockAddr.sin_port=htons(80);
    SockAddr.sin_family=AF_INET;
    SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
    cout << "Connecting...\n";
    if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
        cout << "Could not connect";
        system("pause");
        return 1;
    }
    cout << "Connected.\n";


    char header[]="POST /xampp/tests/file/upload_file.php HTTP/1.1\r\nHost: 127.0.0.1 \r\n Content-Disposition: form-data\r\n uname=sase \r\n  Connection: close\r\n\r\n ";

    send(Socket,header, strlen(header),0);
    char buffer[100000];
    int nDataLength;
    while ((nDataLength = recv(Socket,buffer,100000,0)) > 0){        
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
            cout << buffer[i];
            i += 1;
        }
    }
    closesocket(Socket);
        WSACleanup();
    system("pause");
    return 0;
}

i have this code from the internet, how do i make it send a file using the POST method.
I was at this for more than 5 hours. Please help. Also is there another way of sending http-headers/uploading a with c++ without using other libraries.

Upvotes: 0

Views: 1046

Answers (1)

Dark Falcon
Dark Falcon

Reputation: 44181

In the HTTP protocol, the data for the form goes in the body, not in the header. The header is separated from the body by a blank line (\r\n\r\n). In your code, you're trying to send the data in the header, which is incorrect. You also are using the Content-Disposition header. In fact, you don't need it. You need the Content-Type and Content-Length headers.

char header[]="POST /xampp/tests/file/upload_file.php HTTP/1.1\r\n"
              "Host: 127.0.0.1\r\n"
              "Content-Type: application/x-www-form-urlencoded\r\n"
              "Content-Length: 10\r\n"
              "Connection: close\r\n"
              "\r\n"
              "uname=sase";

There seems to be some confusion about the \n escape sequence. The C++ standard defines \n to be a single LF character in 2.14.3 and says of all escape sequences:

An escape sequence specifies a single character.

8.5.2 confirms this with an example:

char msg[] = "Syntax error on line %s\n"; shows a character array whose members are initialized with a string-literal . Note that because ’\n’ is a single character and because a trailing ’\0’ is appended, sizeof(msg) is 25 . —end example ]

Upvotes: 1

Related Questions