通常情況下,一般很少使用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:
<form action="fileUpload.action" method="post" enctype="multipart/form-data">File:<input type="file" name="sendfile" /><br> FileName:<input type="text" name="filename" /><br> <input type="submit" name="submit" value="Submit" /></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。代碼很粗糙,功能很簡單,只是起個拋磚引玉的作用,希望能對大家有所協助。