c++

如何利用C++ WinHttp进行文件上传

小樊
148
2024-08-29 16:59:09
栏目: 编程语言

要使用C++和WinHttp库进行文件上传,请按照以下步骤操作:

  1. 包含所需的头文件:
#include<iostream>
#include<windows.h>
#include <winhttp.h>
#include <fstream>
#pragma comment(lib, "winhttp")
  1. 定义一个函数来执行文件上传:
bool UploadFile(const std::wstring& url, const std::wstring& filePath) {
    // 初始化WinHttp会话
    HINTERNET hSession = WinHttpOpen(L"MyUserAgent", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    if (!hSession) {
        std::cerr << "Error opening session"<< std::endl;
        return false;
    }

    // 连接到服务器
    HINTERNET hConnect = WinHttpConnect(hSession, url.c_str(), INTERNET_DEFAULT_HTTPS_PORT, 0);
    if (!hConnect) {
        std::cerr << "Error connecting to server"<< std::endl;
        WinHttpCloseHandle(hSession);
        return false;
    }

    // 打开请求
    HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"POST", url.c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
    if (!hRequest) {
        std::cerr << "Error opening request"<< std::endl;
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return false;
    }

    // 设置请求头
    if (!WinHttpAddRequestHeaders(hRequest, L"Content-Type: multipart/form-data; boundary=----MyBoundary\r\n", -1, WINHTTP_ADDREQ_FLAG_ADD)) {
        std::cerr << "Error adding headers"<< std::endl;
        WinHttpCloseHandle(hRequest);
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return false;
    }

    // 读取文件内容
    std::ifstream file(filePath, std::ios::binary | std::ios::ate);
    if (!file.is_open()) {
        std::cerr << "Error opening file"<< std::endl;
        WinHttpCloseHandle(hRequest);
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return false;
    }

    int fileSize = file.tellg();
    file.seekg(0, std::ios::beg);
    char* buffer = new char[fileSize];
    file.read(buffer, fileSize);
    file.close();

    // 构建请求体
    std::string requestBody = "------MyBoundary\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" + std::string(filePath.begin(), filePath.end()) + "\"\r\nContent-Type: application/octet-stream\r\n\r\n";
    requestBody += std::string(buffer, fileSize);
    requestBody += "\r\n------MyBoundary--\r\n";
    delete[] buffer;

    // 发送请求
    if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, (LPVOID)requestBody.c_str(), requestBody.size(), requestBody.size(), 0)) {
        std::cerr << "Error sending request"<< std::endl;
        WinHttpCloseHandle(hRequest);
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return false;
    }

    // 接收响应
    if (!WinHttpReceiveResponse(hRequest, NULL)) {
        std::cerr << "Error receiving response"<< std::endl;
        WinHttpCloseHandle(hRequest);
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return false;
    }

    // 获取响应状态码
    DWORD statusCode = 0;
    DWORD statusCodeSize = sizeof(statusCode);
    if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &statusCode, &statusCodeSize, NULL)) {
        std::cerr << "Error querying headers"<< std::endl;
        WinHttpCloseHandle(hRequest);
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return false;
    }

    // 关闭句柄
    WinHttpCloseHandle(hRequest);
    WinHttpCloseHandle(hConnect);
    WinHttpCloseHandle(hSession);

    // 检查状态码
    if (statusCode != 200) {
        std::cerr << "Server returned status code: "<< statusCode<< std::endl;
        return false;
    }

    return true;
}
  1. 在主函数中调用UploadFile函数:
int main() {
    std::wstring url = L"https://example.com/upload";
    std::wstring filePath = L"C:\\path\\to\\your\\file.txt";

    if (UploadFile(url, filePath)) {
        std::cout << "File uploaded successfully!"<< std::endl;
    } else {
        std::cerr << "Error uploading file"<< std::endl;
    }

    return 0;
}

这个示例将文件上传到指定的URL。请确保将urlfilePath变量更改为实际值。注意,这个示例仅适用于Windows平台。

0
看了该问题的人还看了