簡體   English   中英

Cocos2d-x-如何使用PHP將文件上傳到服務器?

[英]Cocos2d-x - How to upload file to server using PHP?

我想使用CCHttpClient使用POST方法上傳文件。

服務器已經准備好接收文件,因為我使用Java,並且Objective C已經成功上傳。

我想知道如何將POST數據制作到cocos2d-x中的文件中。

std :: string path = CCFileUtils :: sharedFileUtils () -> getWritablePath () + "temp.png";
unsigned long buff = 0; 
unsigned char * pBuffer = CCFileUtils :: sharedFileUtils () -> getFileData (path.c_str (), "r", & buff); 

首先以未簽名的char數據文件的形式制成,

const char * fileBinary = (const char *) pBuffer; 

具有強制轉換為const char格式。

以下已使其成為POST數據。

std :: string boundary = "--------------------------- 14737809831466499882746641449";
std :: string str = "\ r \ n--" + boundary + "\ r \ n"; 
str = str + "Content-Disposition: attachment; name = \" upload_file \ "; filename = \" 11.png \ "\ r \ n"; 
str = str + "Content-Type: application / octet-stream \ r \ n \ r \ n"; 
str = str + fileBinary; <- This is the data portion of the file. 
str = str + "\ r \ n--" + boundary + "- \ r \ n"; 

通過轉移到POST方法來執行此操作,將上傳文件,但上傳的文件數據只有8個字節。

如何創建數據發送文件?

這是完整的代碼。

std::string path = CCFileUtils::sharedFileUtils()->getWritablePath() + "temp.png";
unsigned long buff = 0;
unsigned char* pBuffer = CCFileUtils::sharedFileUtils()->getFileData(path.c_str(), "r", &buff);

const char* fileBinary = (const char*)pBuffer;


std::string boundary = "---------------------------14737809831466499882746641449";
std::string bound = boundary;
std::vector<std::string> headers;
headers.push_back("Content-Type: multipart/form-data; boundary="+bound);

std::string str = "\r\n--" + boundary + "\r\n";
str = str + "Content-Disposition: attachment; name=\"upload_file\"; filename=\"11.png\"\r\n";
str = str + "Content-Type: application/octet-stream\r\n\r\n";
str = str + fileBinary;
str = str + "\r\n--" + boundary + "--\r\n";


CCHttpRequest* request = new CCHttpRequest();
request->setUrl("SERVER ADDRESS"); 
request->setHeaders(headers);
request->setRequestType(CCHttpRequest::kHttpPost);
request->setRequestData(str.c_str(), strlen(str.c_str()));
request->setResponseCallback(this, httpresponse_selector(MainScene::complete));
request->setTag("UP IMAGE");
CCHttpClient::getInstance()->send(request);
request->release();

PNG的第9個字節為零。

當您在此處串聯文件數據時:

str = str + fileBinary;

它只會被復制到第一個零。

您應該能夠像這樣構造一個“二進制”字符串:

 std::string(fileBinary, lengthOfFileBinary)

因為此構造函數可以創建包含空字節的字符串。
您需要從strlen以外的其他地方獲取大小,因為strlen對於二進制數據毫無意義。
(Cocos可能具有返回文件大小的函數)。

那你可以用

request->setRequestData(str.data(), str.size());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM