我有带有 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);