curl的http上传文件代码
int http_post_file(const char *url, const char *user, const char *pwd, const char *filename)
{
assert(url != NULL);
assert(user != NULL);
assert(pwd != NULL);
assert(filename != NULL);
int ret = -1;
CURL *curl = NULL;
CURLcode code;
CURLFORMcode formCode;
int timeout = 15;
#define CHECK_FORM_ERROR(x) /
if ((formCode = (x)) != CURL_FORMADD_OK) /
{ /
fprintf(stderr, "curl_formadd[%d] error./n", formCode); /
goto out; /
}
#define CHECK_SETOPT_ERROR(x) /
if ((code = (x)) != CURLE_OK) /
{ /
fprintf(stderr, "curl_easy_setopt[%d] error./n", code); /
goto all; /
}
struct curl_httppost *post=NULL;
struct curl_httppost *last=NULL;
struct curl_slist *headerlist=NULL;
CHECK_FORM_ERROR( curl_formadd(&post, &last, CURLFORM_COPYNAME, "user",
CURLFORM_COPYCONTENTS, user,
CURLFORM_END));
CHECK_FORM_ERROR( curl_formadd(&post, &last, CURLFORM_COPYNAME, "password",
CURLFORM_COPYCONTENTS, pwd,
CURLFORM_END));
CHECK_FORM_ERROR( curl_formadd(&post, &last, CURLFORM_COPYNAME, "file",
CURLFORM_FILE, filename,
CURLFORM_END));
CHECK_FORM_ERROR( curl_formadd(&post, &last,
CURLFORM_COPYNAME, "submit",
CURLFORM_COPYCONTENTS, "upload",
CURLFORM_END));
curl = curl_easy_init();
if(curl == NULL)
{
fprintf(stderr, "curl_easy_init() error./n");
goto out;
}
CHECK_SETOPT_ERROR(curl_easy_setopt(curl, CURLOPT_HEADER, 0));
CHECK_SETOPT_ERROR(curl_easy_setopt(curl, CURLOPT_URL, url));
CHECK_SETOPT_ERROR(curl_easy_setopt(curl, CURLOPT_HTTPPOST, post));
CHECK_SETOPT_ERROR(curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout));
code = curl_easy_perform(curl);
if(code != CURLE_OK)
{
fprintf(stderr, "curl_easy_perform[%d] error./n", code);
goto all;
}
ret = 0;
all:
curl_easy_cleanup(curl);
out:
curl_formfree(post);
return ret;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。