(7条消息) curl post表单上传文件(C++)

最近测试如何上传文件到服务器。原来传照片一致通过binary 形式传文件,或者把图片base64编码传图片。一致没有用form-data 表单形式发送数据,今天尝试下如何使用libcurl提供的API上传文件。

Sample code:

#include <iostream>
#include <curl/curl.h>
#include <string.h>

using namespace std;
//回调函数  得到响应内容
int write_data(void* buffer, int size, int nmemb, void* userp){
    std::string * str = dynamic_cast<std::string *>((std::string *)userp);
    str->append((char *)buffer, size * nmemb);
    return nmemb;
}
int upload(string url, string &body,  string* response);

int main(int argc, char** argv){

std::string body;
std::string response;

    int status_code = upload("http://172.28.28.17:80/files/deviceupload", body, &response);
if (status_code != CURLcode::CURLE_OK) {
return -1;
}
    cout << body << endl;
cout << response << endl;

return 0;
}

int upload(string url, string &body,  string* response)
{
    CURL *curl;
    CURLcode ret;
    curl = curl_easy_init();
    struct curl_httppost* post = NULL;
    struct curl_httppost* last = NULL;
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, (char *)url.c_str());           //指定url
        curl_formadd(&post, &last, CURLFORM_PTRNAME, "path", CURLFORM_PTRCONTENTS, "device_cover", CURLFORM_END);//form-data key(path) 和 value(device_cover)
        curl_formadd(&post, &last, CURLFORM_PTRNAME,  "file", CURLFORM_FILE, "./test.jpg",CURLFORM_FILENAME, "hello.jpg", CURLFORM_END);// form-data key(file) "./test.jpg"为文件路径  "hello.jpg" 为文件上传时文件名
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);                     //构造post参数
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);          //绑定相应
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)response);        //绑定响应内容的地址

        ret = curl_easy_perform(curl);                          //执行请求
        if(ret == 0){
            curl_easy_cleanup(curl);
            return 0;
        }
        else{
            return ret;
        }
    }
else{
        return -1;
}
}

编译:

    g++  -O2 -Wall -Wno-write-strings  -D_LINUX  -L../libcurl/lib -I../libcurl/include  -std=c++11  ./test_main.cpp   -L../libcurl/lib -lcurl -lssl -lcrypto  -ldl -pthread -o sample_X86_64

如果文件路径不对 会不执行请求。

(0)

相关推荐