gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:06:38 26 4
gpt4 key购买 nike

#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 协议(protocol)将文件从用户发送到服务器

最佳答案

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,并将Content-Length设置为文件的大小。

    char *header="POST /xampp/tests/file/check.php HTTP/1.1\r\n"
    "Host: 127.0.0.1\r\n"
    "Content-Type: application/octet-stream\r\n"
    "Content-Length: ...\r\n" // <-- substitute with the actual file size
    "Connection: close\r\n"
    "\r\n";
    send(Socket,header, strlen(header),0);

    // send the raw file bytes here...

您使用哪个取决于服务器能够接受的内容。

关于c++ - 使用c++使用http POST发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26070899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com