1. 程式人生 > >cocos Httpclient 上傳檔案到伺服器

cocos Httpclient 上傳檔案到伺服器

廢話不多說、直接貼程式碼!
#include "Test01060Http.h"
#include <Shlwapi.h>
#include "stdio.h"




Test01060Http::Test01060Http()
{
}




Test01060Http::~Test01060Http()
{
}


bool Test01060Http::init()
{
Layer::init();


UploadPictures();


return true;
}
#define MYDATA "this is extra data from client"
void  Test01060Http::UploadPictures()
{
        network::HttpClient* http = network::HttpClient::getInstance();
network::HttpRequest* req = new network::HttpRequest;


req->setRequestType(network::HttpRequest::Type::POST);
req->setUrl("http:///subassembly/uploadPicterController/upload.html");
req->setResponseCallback(CC_CALLBACK_2(Test01060Http::onHttpRequestCompleted, this));


std::string pathKey = FileUtils::sharedFileUtils()->fullPathForFilename("b2de9c82d158ccbf0881c1d01dd8bc3eb135411e.jpg");
CCLOG("path = %s",pathKey.c_str());


//auto sifile = PathFindFileName(pathKey);
    Data imgdata = FileUtils::getInstance()->getDataFromFile(pathKey);

LPTSTR a = (LPTSTR)pathKey.c_str();

        /  / 拿到最後一個斜槓最後檔名例項!

std::string B = "C:\\Windows\\System32/notepad.exe";
ssize_t pos = B.find_last_of("/");
std::string cach_filename;
if (pos !=std::string::npos)
{
cach_filename = B.substr(pos + 1);
}
else
{
cach_filename = B;
}

CCLOG("B = %s", cach_filename.c_str());

        //拿到圖片資料

        long buff = 0;
unsigned char * pBuffer = FileUtils::sharedFileUtils()->getFileData(pathKey.c_str(),"rb", &buff);
const char* fileBinary = (const char*)pBuffer;
CCLOG("fileBinary %s = ", fileBinary);
       //得到圖片 檔案流大小
std::string strBin = std::string(fileBinary, buff);
       //設定 http headers  引數 和  資料流
std::string boundary = "----------------WebKitFormBou3123ndaryEm5WNw6hGiQUBpng";
std::string bound = boundary;
std::vector<std::string> headers;
headers.push_back("Content-Type:multipart/form-data; boundary = " + bound);
std::string strdata = strBin;
std::string str = "\r\n--" + boundary + "\r\n";
str = str + "Content-Disposition: form-data; name=\"file\"; filename=\"paoku1.png\"\r\n";
str = str + "Content-Type: application/octet-stream\r\n\r\n";
str = str + strBin;
str = str + "\r\n--" + boundary + "--\r\n";

// 設定設定Header

req->setHeaders(headers);

     //設定 RequesData 
req->setRequestData(str.data(), str.size());

CCLOG("str data = %s \n str .size = %d \n", str.data(), str.size());

//傳送 

http->send(req);

//關閉

req->release();
};
void  Test01060Http::onHttpRequestCompleted(network::HttpClient* client, network::HttpResponse* response)
{
if (!response->isSucceed())
{
CCLOG("error");
CCLOG("error buffer: %s", response->getErrorBuffer());
CCLOG("error code: %d", (int)response->getResponseCode());
return;
}
CCLOG("login success");
};