使用c ++使用http POST发送文件

时间:2014-09-27 03:08:34

标签: c++ http post http-headers

#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/check.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"
              "text1=sase";
    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();
        cout<<endl<<endl;
    system("pause");
    return 0;
}

这是我目前的代码。它发送text1,但现在我希望它发送一个文件(位于:C:\ Users \ Wade \ Downloads \ Documents)。我怎么做 如何使用HTTP POST协议将文件从用户发送到服务器

3 个答案:

答案 0 :(得分:4)

application/x-www-form-urlencoded仅支持name=value对。要POST文件,您必须:

  1. 请改用multipart/form-data

    char *header="POST /xampp/tests/file/check.php HTTP/1.1\r\n"
          "Host: 127.0.0.1\r\n"
          "Content-Type: multipart/form-data; boundary=myboundary\r\n"
          "Connection: close\r\n"
          "\r\n"
          "--myboundary\r\n"
          "Content-Type: application/octet-stream\r\n"
          "Content-Disposition: form-data; name=\"myfile\"; filename=\"myfile.ext\"\r\n"
          "Content-Transfer-Encoding: 8bit\r\n"
          "\r\n";
    send(Socket,header, strlen(header),0);
    
    // send the raw file bytes here...
    
    char *footer = "\r\n"
               "--myboundary--\r\n";
    send(Socket, footer, strlen(footer), 0);
    
  2. 将文件内容作为整个POST内容发送,将Content-Type设置为文件的实际类型或application/octet-stream,然后设置{{ 1}}到文件的大小。

    Content-Length
  3. 您使用哪一个取决于服务器能够接受的内容。

答案 1 :(得分:1)

使用此代码

#define DATA_SIZE 1024*1024*10 //10MB
#define MAXLINE 409600

char * servIP = "127.0.0.1";
int servPort = 80;

ssize_t send_file(char *fileDir, char *filename)
{
    char *packet;
    char pre_body[1024], post_body[1024];
    char sendline[MAXLINE + 1];
    char boundary[] ="----WebKitFormBoundaryu8FzpUGNDgydoA4z";

    char *bodyline = calloc(sizeof(char), DATA_SIZE);
    char *fileBuf = calloc(sizeof(char), DATA_SIZE);
    int sock = makeSocket();

    printf("send file name : %s\n", filename);

    FILE *fp = fopen(fileDir, "r");
    if(fp == NULL){
        printf("file can't read\n");
        fclose(fp);
        return -1;
    }

    fseek(fp, 0, SEEK_END);
    int file_size = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    if(fread(fileBuf, 1, file_size, fp) == -1){
        printf("fread error\n");
    }
    // make body
    sprintf(pre_body, "--%s\r\nContent-Disposition: form-data; name=\"pdata\"\r\n\r\n"
        "%s\r\n--%s\r\nContent-Disposition: form-data; name=\"flag\"\r\n\r\n"
        "%s\r\n--%s\r\nContent-Disposition: form-data; name=\"upfile\";filename=\"%s\"\r\n"
        "Content-Type:application/octect-stream\r\n\r\n"
        ,  boundary, "postdata", boundary,"no", boundary, filename);

    sprintf(post_body, "\r\n--%s--\r\n", boundary);

    int pre_len = strlen(pre_body);
    int post_len = strlen(post_body);
    int body_len = pre_len + file_size + post_len;

    memcpy(bodyline, pre_body, pre_len);
    memcpy(bodyline+pre_len, fileBuf, file_size);
    memcpy(bodyline+pre_len+file_size, post_body, post_len);

    //make header
    sprintf(sendline, "POST /FileUpload.jsp HTTP/1.1\r\n"
        "Host: %s\r\nConnection: keep-alive\r\n"
        "Content-Length: %d\r\n"
        "Content-Type: multipart/form-data; boundary=%s\r\n\r\n", servIP, body_len, boundary);
    int head_len = strlen(sendline);
    int packet_len = head_len+body_len;

    //join header + body
    packet=calloc(1, head_len+body_len+1);
    memcpy(packet, sendline, head_len);
    memcpy(packet+head_len, bodyline, body_len);


    write(sock, packet, packet_len);

    fclose(fp);
    free(packet);
    close(sock);
    return 0;
}

int makeSocket(){
    struct sockaddr_in servAddr;
    int sock;
    char ip[20];
    /* Create areliable, stream socket using TCP */
    if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
        printf("socket create failed\n");

    struct hostent *host_entry;
    host_entry = gethostbyname(servIP);
    for(ndx = 0; NULL != host_entry->h_addr_list[ndx]; ndx++){
        strcpy(ip, inet_ntoa(*(struct in_addr*)host_entry->h_addr_list[ndx]));
    }

    memset(&servAddr, 0, sizeof(servAddr)); //Zero ou structure
    servAddr.sin_family = AF_INET; //Internet address family
    servAddr.sin_addr.s_addr = inet_addr(ip); //Server IP address
    servAddr.sin_port = htons(servPort);//Server port

    /* Establish the connection to the web server */
    if(connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
            printf("connet() failed\n");

    return sock;
}

答案 2 :(得分:0)

我去上班了。这里的代码没有读取文件。

char outtemp[];
     ifstream inFile("c:\\temp.html");
     ofstream outtemp("temp");
     while(inFile.good()){
                          getline(inFile,buffer);
                          outtemp<<buffer;
                          }
     inFile.close();//close files after using
     outtemp.close();//close files after using




    char data[]=
    "\r\n"
    "--border287032381131322\r\n"
    "Content-Disposition: form-data; name=\"this\" \r\n\r\n" 
    "aasda\r\n\r\n"
    "--border287032381131322\r\n"
    "Content-Disposition: form-data; name=\"file\"; filename=\"C:\\temp.html\" Content-Type: text/plain \r\n\r\n" 
char data2[]=
    "<h1>Home page on main server</h1>\r\n\r\n"
    "--border287032381131322--\r\n";

    char header[] =
    "POST /xampp/tests/winsock_test/do.php HTTP/1.1\r\n"
    "Host: 127.0.0.1\r\n"
    "Content-Type: multipart/form-data; boundary=border287032381131322\r\n"
    "Connection: close\r\n";
    strcat(header,data1);
strcat(header,outtemp);
strcat(header,data2)
    cout<<"----------Sending----------------"<<endl<<header<<endl<<"size:"<<sizeof(data)<<endl<<"--------------sending end------------"<<endl<<endl;// for debug

    send(Socket,header, strlen(header),0);