form方式向Http服务器提交图片的示例代码

#include <string>
#include <curl/curl.h>

/*
Title: form方式向Http服务器提交图片
Environment: 
 [1]VS2010SP1
 [2]libcurl 7.36
参考资料
 [1]《cURL / libcurl / API / Examples / postit2.c》
 http://curl.haxx.se/libcurl/c/postit2.html

<form method="post" action="http://172.16.1.155:82/upload/posShowImg" enctype="multipart/form-data">
<input type="file" name="photo" id="add_newsImgFile"/>
</form>
这里模拟提交了action和photo两个字段。

代码调用示例:
UploadImage("http://172.16.1.155:82/upload/posShowImg","d:\\再老也得养政府.jpg",
"http://172.16.1.155:82/upload/posShowImg",outData); 
*/
size_t write_callback( void *ptr, size_t size, size_t nmemb, void *outBuffer )  
{  
	int len = size * nmemb;  
	char *temp = new char[len+1];     
	memcpy(temp,ptr,len);  
	temp[len]=0;  
	reinterpret_cast<std::string *>(outBuffer)->append(temp);  
	delete temp;  
	return len;  
}  

int UploadImage(char* pPostURL, char* pImageFileName, char* pAction, std::string &strOutData) 
{
	CURL *curl;
	CURLcode res;

	curl = curl_easy_init();
	strOutData="";

	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);//write_data
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strOutData);

	struct curl_httppost *formpost = 0;
	struct curl_httppost *lastptr  = 0;
	curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "photo", CURLFORM_FILE, pImageFileName,CURLFORM_CONTENTTYPE, "image/jpeg", CURLFORM_END);
	curl_formadd(&formpost, &lastptr,CURLFORM_COPYNAME, "action",CURLFORM_COPYCONTENTS, pAction,CURLFORM_END);
	curl_easy_setopt(curl, CURLOPT_URL, pPostURL);
	curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);

	res = curl_easy_perform(curl);
	curl_easy_cleanup(curl);
	curl_formfree(formpost);
	return res;
}




你可能感兴趣的:(form方式向Http服务器提交图片的示例代码)