先看HTML代码:
<html> <head> <meta http-equiv=content-type content="text/html;charset=gb2312"> <title>File Upload</title> </head> <body> <form action="/?fileupload" method="post" id="uplodfile" name="uploadfile" enctype="multipart/form-data" > <input type="file" id="file" name="upload" style="width:300px"> <input name="submit" type="submit" value="OK" > </form> </body> </html> |
相应的C代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <curl/curl.h>
#define MAX_BUFF_LEN 1048576 /*1M*/
#define POST_URL "http://127.0.0.1/?fileupload"
int check_file_existed(char *filename)
{
struct stat st;
return (stat( filename, &st )==0 && S_ISREG(st.st_mode));
}
int get_file_size(char *filename)
{
int file_len = 0;
int fd = 0;
fd = open(filename, O_RDONLY);
if(fd < 0)
{
perror("open");
exit(-1);
}
file_len = lseek(fd, 0, SEEK_END);
if(file_len < 0)
{
perror("lseek");
exit(-1);
}
return file_len;
}
int http_post_file(const char *url, const char *filename)
{
CURL *curl = NULL;
CURLcode res;
struct curl_httppost *post=NULL;
struct curl_httppost *last=NULL;
struct curl_slist *headerlist=NULL;
if(filename == NULL || url == NULL)
return -1;
printf("URL: %s/n", url);
printf("filename: %s/n", filename);
/* Add simple file section */
if( curl_formadd(&post, &last, CURLFORM_COPYNAME, "upload",
CURLFORM_FILE, filename, CURLFORM_END) != 0)
{
fprintf(stderr, "curl_formadd error./n");
goto out;
}
/* Fill in the submit field too, even if this is rarely needed */
curl_formadd(&post, &last,
CURLFORM_COPYNAME, "submit",
CURLFORM_COPYCONTENTS, "OK",
CURLFORM_END);
//curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if(curl == NULL)
{
fprintf(stderr, "curl_easy_init() error./n");
goto out;
}
curl_easy_setopt(curl, CURLOPT_HEADER, 0);
curl_easy_setopt(curl, CURLOPT_URL, url); /*Set URL*/
curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
int timeout = 5;
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1);
res = curl_easy_perform(curl);
if(res != CURLE_OK)
{
fprintf(stderr, "curl_easy_perform[%d] error./n", res);
goto out;
}
curl_easy_cleanup(curl);
out:
curl_formfree(post);
//curl_global_cleanup();
return 0;
}
int main(int argc, char *argv[])
{
char buff[MAX_BUFF_LEN]={0};
//Check Argument
//argv[1] upload filename
if(argc != 2)
{
fprintf(stderr, "Usage: %s filename/n", argv[0]);
return 1;
}
//Check File Existed
if(!check_file_existed(argv[1]))
{
fprintf(stderr, "File Not Existed./n");
return 1;
}
//Check File Size
if( get_file_size(argv[1]) >= MAX_BUFF_LEN)
{
fprintf(stderr, "File Size is Big!/n");
return 1;
}
//POST File
http_post_file(POST_URL, argv[1]);
return 0;
}