通常情况下,一般很少使用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:
File: FileName:
- <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);
代码经过测试,可以使用,但是需要提前配置好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