c++ http 图片上传
时间: 2023-09-12 16:06:04 浏览: 202
symbian C++ Flickr_Upload_v1.0 PDF
实现HTTP图片上传可以分为以下几个步骤:
1. 打开待上传的图片文件,并读取文件内容。
2. 构造HTTP请求报文,设置请求头部信息。
3. 将图片内容作为HTTP请求体,并发送HTTP请求。
4. 接收HTTP响应,判断上传是否成功。
下面是一个简单的C++代码示例:
```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
// 初始化WinSock库
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cout << "WSAStartup failed!" << endl;
return -1;
}
// 创建socket
SOCKET clientSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSock == INVALID_SOCKET) {
cout << "Failed to create socket!" << endl;
WSACleanup();
return -1;
}
// 设置服务器地址和端口号
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 服务器IP地址
serverAddr.sin_port = htons(80); // 服务器端口号
// 连接服务器
if (connect(clientSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) {
cout << "Failed to connect to server!" << endl;
closesocket(clientSock);
WSACleanup();
return -1;
}
// 打开待上传的图片文件
ifstream fin("test.jpg", ios::binary);
if (!fin.is_open()) {
cout << "Failed to open file!" << endl;
closesocket(clientSock);
WSACleanup();
return -1;
}
// 读取文件内容
fin.seekg(0, fin.end);
int fileSize = fin.tellg();
fin.seekg(0, fin.beg);
char* fileBuf = new char[fileSize];
fin.read(fileBuf, fileSize);
fin.close();
// 构造HTTP请求报文
string boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"; // 分隔符
string contentType = "multipart/form-data; boundary=" + boundary; // 请求头部信息
string body = "--" + boundary + "\r\n";
body += "Content-Disposition: form-data; name=\"file\"; filename=\"test.jpg\"\r\n";
body += "Content-Type: image/jpeg\r\n\r\n";
body += fileBuf;
body += "\r\n--" + boundary + "--\r\n";
string request = "POST /upload HTTP/1.1\r\n";
request += "Host: 127.0.0.1\r\n";
request += "Content-Type: " + contentType + "\r\n";
request += "Content-Length: " + to_string(body.size()) + "\r\n\r\n";
request += body;
// 发送HTTP请求
if (send(clientSock, request.c_str(), request.size(), 0) == SOCKET_ERROR) {
cout << "Failed to send request!" << endl;
closesocket(clientSock);
WSACleanup();
return -1;
}
// 接收HTTP响应
char recvBuf[1024];
int recvLen = 0;
while ((recvLen = recv(clientSock, recvBuf, sizeof(recvBuf), 0)) > 0) {
cout.write(recvBuf, recvLen);
}
// 关闭socket
closesocket(clientSock);
// 释放内存
delete[] fileBuf;
// 清理WinSock库
WSACleanup();
return 0;
}
```
以上代码演示了如何上传名为test.jpg的图片文件到服务器上,其中服务器地址为127.0.0.1,端口号为80。需要注意的是,上传的图片文件需要放在与可执行文件相同的目录下,且服务器需要有一个/upload的接口来接收上传请求。
阅读全文