C libcurl force“Content-Type”

时间:2013-02-04 10:55:36

标签: c libcurl

我有使用libcurl的以下C代码将文件上传到我的网络服务器,几乎没问题我需要上传的内容是“Content-Type:application / vnd.ms-excel”,但它获得了“Content-Type” :application / octet-stream“,尝试使用标题,但现在运气好了。在PHP中使用curl很简单,我只需要curl_setopt($ch, CURLOPT_POSTFIELDS, array("importfile" => "@".$file_path . ";type=application/vnd.ms-excel"并且正常工作。有帮助吗?想法?

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

int main(int argc, char *argv[])
{
  CURL *curl;
  CURLcode res;

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

  curl_global_init(CURL_GLOBAL_ALL);

  curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "importfile", CURLFORM_FILE, "document.csv", CURLFORM_END);
  curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "action", CURLFORM_COPYCONTENTS, "upload", CURLFORM_END);

  curl = curl_easy_init();
  headerlist = curl_slist_append(headerlist, buf);
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://www.myhost.com/upload/upload.php");
    if ( (argc == 2) && (!strcmp(argv[1], "noexpectheader")) )
      curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);

    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 (headerlist);
  }
  return 0;
}

尝试将HEADER添加为“Content-Type:application / vnd.ms-excel”,但是不对,我得到:

Content-Type: application/vnd.ms-excel
标题中的

但我需要:

------WebbbbFormBoundaryXaI1UTNwqAyKWvLT
Content-Disposition: form-data; name="importfile"; filename="document.csv"
Content-Type: application/vnd.ms-excel

相反,我得到:

------WebbbbFormBoundaryXaI1UTNwqAyKWvLT
Content-Disposition: form-data; name="importfile"; filename="document.csv"
Content-Type: application/octet-stream

感谢您的帮助,回答是:

curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "importfile", CURLFORM_FILE, "document.csv", CURLFORM_CONTENTTYPE, "application/vnd.ms-excel", CURLFORM_END);

1 个答案:

答案 0 :(得分:4)

您正在寻找curl_formadd选项CURLFORM_CONTENTTYPE