使用POST libcurl上传文件(非直接)

时间:2014-03-03 11:25:23

标签: file-upload curl http-post libcurl

您希望将一个input.zip文件以及此文件的xml描述上传到服务器。这是我要在CURLOPT_POSTFIELDS中发送的xml描述部分,

<data_file>
<archive>"true"</archive>
<data_type_id> "42f7710d-9399-45d8-a61f-a018bb6c33f6""</data_type_id>
<data_file_name> "INPUT.zip"</data_file_name>
<description>..</description>
<uploaded>true</uploaded>
<job_id> job_id</job_id>
</data_file>

这是libcurl部分。我不确定我们是否可以在同一个请求中发送POST参数和Postform。

    struct curl_httppost *formpost=NULL;
    struct curl_httppost *lastptr=NULL;
    struct curl_slist *headers=NULL;
    static const char buf[] = "Expect:";

    curl_global_init(CURL_GLOBAL_ALL);

     /* Fill in the file upload field */
     curl_formadd(&formpost,
             &lastptr,
             CURLFORM_COPYNAME, "sendfile",
             CURLFORM_FILE, filepathinput.c_str(),
             CURLFORM_END);

     /* Fill in the filename field */
     curl_formadd(&formpost,
             &lastptr,
             CURLFORM_COPYNAME, "INPUT.zip",
             CURLFORM_COPYCONTENTS, filepathinput.c_str(),
             CURLFORM_END);


     /* Fill in the submit field too, even if this is rarely needed */
     curl_formadd(&formpost,
             &lastptr,
             CURLFORM_COPYNAME, "submit",
             CURLFORM_COPYCONTENTS, "send",
             CURLFORM_END);


      curl = curl_easy_init();
       headers = curl_slist_append(headers, buf);
       headers = curl_slist_append(headers, "Content-Type: multipart/form-data");


 if(curl) {

    curl_easy_setopt(curl, CURLOPT_VERBOSE, true);

    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_USERPWD,_loginCBstring.c_str());
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);


 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, xmldescription.c_str());
     curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(xmldescription.c_str()));

    _res = curl_easy_perform(curl);

    if(_res != CURLE_OK)
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(_res));

    curl_easy_cleanup(curl);

    curl_formfree(formpost);
    curl_slist_free_all (headers);
}

提前很多!

0 个答案:

没有答案