在做一个项目的时候,有一个上传文件到服务器的功能,考虑到2dx是跨平台的,那么这些功能也最好是跨平台的,就用了2dx自带的curl库来实现(貌似Cocos2dx的CCHttpClient类没有封装上传文件的功能),现把代码贴出来,大家共勉.
头文件:
#include "cocos2d.h"
using namespace cocos2d;
using namespace std;
class uploadFile : public CCObject
{
public:
static uploadFile *m_inst;
static uploadFile *GetInst();
void UpLoadFile(string photoPath);
static size_t write_data(uint8_t *dataBack, size_t size, size_t nmemb, void *userp);
};
cpp文件:
#include "uploadFile.h"
#include "curl.h"
uploadFile* uploadFile::m_inst = NULL;
uploadFile* uploadFile::GetInst()
{
if(!m_inst)
{
m_inst = new uploadFile();
return m_inst;
}
return NULL;
}
void uploadFile::UpLoadFile(string photoPath)
{
CCLOG("IN uploadFile::UpLoadFile(");
CURLcode cURLcode;
CURL *cURL;
//Init
cURLcode = curl_global_init(CURL_GLOBAL_SSL);
if(CURLE_OK != cURLcode)
{
curl_global_cleanup();
return ;
}
cURL = curl_easy_init();
if(!cURL)
{
curl_easy_cleanup(cURL);
curl_global_cleanup();
return ;
}
curl_httppost *post = NULL;
curl_httppost *last = NULL;
//上传的文件的全路径并指定类型
curl_formadd(&post, &last,CURLFORM_COPYNAME,"photo",
CURLFORM_FILE,photoPath.c_str(),
CURLFORM_CONTENTTYPE,"Image/png",CURLFORM_END);
设置多个参数
//curl_formadd(&post, &last,CURLFORM_COPYNAME,"username",
// CURLFORM_COPYCONTENTS,"你好",CURLFORM_END);
curl_easy_setopt(cURL, CURLOPT_URL,"服务器地址");
curl_easy_setopt(cURL, CURLOPT_TIMEOUT,10);//超时时间10秒
curl_easy_setopt(cURL, CURLOPT_HTTPPOST,post);//请求方式POST
curl_easy_setopt(cURL, CURLOPT_WRITEFUNCTION,write_data); //设置回调
curl_easy_setopt(cURL, CURLOPT_VERBOSE,1); //非零值表示你想CURL报告每一件意外的事情
curl_easy_perform(cURL);
curl_easy_cleanup(cURL);
curl_global_cleanup();
}
size_t uploadFile::write_data(uint8_t *dataBack, size_t size, size_t nmemb, void *user_p)
{
string szData = string((char*)dataBack); //返回的结果
return 0;
}