通常情況下,一般很少使用C語言來直接上傳文件,但是遇到使用C語言編程實現文件上傳時,該怎么做呢?
借助開源的libcurl庫,我們可以容易地實現這個功能。Libcurl是一個免費易用的客戶端URL傳輸庫,主要功能是用不同的協議連接和溝通不同的服務器,libcurl當前支持DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP,IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet andTFTP。libcurl同樣支持HTTPS證書授權,HTTP POST, HTTP PUT, FTP 上傳, HTTP基本表單上傳,代理,cookies,和用戶認證等。下面借鑒libcurl官網的例子完成簡單的文件上傳。
模擬要實現的文件上傳FORM:
其中,fileUpload.action為文件處理文件上傳的接口,根據實際需要配置,這里只是一個例子。
C語言HTTP上傳文件的代碼如下:
#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); /* Fill in the file upload field */ curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "sendfile", CURLFORM_FILE, "D:\\sign.txt", CURLFORM_END); /* Fill in the filename field */ curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "filename", CURLFORM_COPYCONTENTS, "sign.txt", CURLFORM_END); /* Fill in the submit field too, even if this is rarely needed */ curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "submit", CURLFORM_COPYCONTENTS, "Submit", CURLFORM_END); curl = curl_easy_init(); /* initalize custom header list (stating that Expect: 100-continue is not wanted */ headerlist = curl_slist_append(headerlist, buf); if(curl) { /* what URL that receives this POST */ curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:8080/fileUpload.action"); if ( (argc == 2) && (!strcmp(argv[1], "noexpectheader")) ) /* only disable 100-continue header if explicitly requested */ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); /* always cleanup */ curl_easy_cleanup(curl); /* then cleanup the formpost chain */ curl_formfree(formpost); /* free slist */ curl_slist_free_all (headerlist); } return 0; }
代碼經過測試,可以使用,但是需要提前配置好Libcur庫,以及編譯環境,這個自行google。代碼很粗糙,功能很簡單,只是起個拋磚引玉的作用,希望能對大家有所幫助。
來自:http://blog.csdn.net/sxwyf248/article/details/7984776
VC2013下,使用curl:
http://www.tuicool.com/articles/A73ARr
較細:http://blog.csdn.net/mjpassion/article/details/6290912
Visual2012:http://www.howzhi.com/course/3387/lesson/43112
參考:http://www.cppblog.com/len/archive/2008/06/21/54229.html
使用libcurl模擬form表單上傳的問題:
http://bbs.csdn.net/topics/390817077
在C語言程序中使用cURL庫(libcurl):
http://demon.tw/programming/c-libcurl.html