Cocos2dx demo for uploading simple files to the php server

Source: Internet
Author: User
Recently I just finished writing a simple test program that uploads data from the client to the php server. The code can be copied and run directly. before reading the code, it is best to spend some time learning about php and libcurl, it won't take too long. Because I am not very familiar with php when I create a form, all the libcurl

Recently I just finished writing a simple test program that uploads data from the client to the php server. The code can be copied and run directly. before reading the code, it is best to spend some time learning about php and libcurl, it won't take too long. Because I am not very familiar with php when I create a form, all the libcurl

I have just finished writing a cocos2dx file and uploaded it from the client to php.ServerOfSimpleTest Program, code can be copied and run directly


Before reading the code, it is best to take some time to learn about php and libcurl. It does not take too long because I am not very familiar with php, it took me a while to solve a problem when I pieced the form using libcurl. The code below isSimpleThe demo code is a bit rough, but it has little impact on everyone's understanding.

I use Apache in XAMMPServer, Put the php script in the \ xampp \ htdocs \ directory, and create upload in the current directoryFileFolder used to store the uploadedFile

1:

ReceiveFile. php

 File*/$ Type = array ("rar", "zip", "txt", "c", "JPG");/* obtain the uploadFileInformation * // $ upfile = & $ HTTP_POST_FILES ['file']; $ upfile = $ _ FILES ["file"]; echo "Upload :". $ _ FILES ["file"] ["name"]."
"; Echo" Type: ". $ _ FILES [" file "] [" type "]."
& Quot; echo & quot; Size: & quot;. ($ _ FILES [& quot; file & quot;] [& quot; size & quot;]/1024). & quot; Kb
"; Echo" Temp file: ". $ _ FILES [" file "] [" tmp_name "]."
";/* GetFileExtension name function */function fileext ($ filename) {return substr (strrchr ($ filename ,'. '), 1);} // echo "Temp file :". fileext ($ upfile ['name']."
";/* Determine the uploadFileType */if (! In_array (strtolower (fileext ($ upfile ['name']), $ type) {$ text = implode (",", $ type); echo "sorry, you can only upload the following typesFile: ", $ Text ,"
";} Else {/* settingsFileName: "date _FileName "*/$ dest = $ dest_dir. '/'. date (" ymdHis ")." _ ". $ upfile ['name'];/* Move uploadFileTo specifiedFileFolder */$ state = move_uploaded_file ($ upfile ['tmp _ name'], $ dest); if ($ state) {print ("FileUploaded successfully!
"); Print ("FileName: ". $ dest ."
"); Print (" uploadedFileSize: ". (round ($ upfile ['SIZE']/, 2)." KB
");} Else {/* handle error messages */switch ($ upfile ['error']) {case 1: die (" UploadFileThe size exceeds the limit of php. ini: upload_max_filesize.
"); Case 2: die (" UploadFileThe size exceeds the MAX_FILE_SIZE limit.
"); Case 3: die ("FileOnly partially uploaded
"); Case 4: die (" NoFileUploaded
"); Case 5: die (" cannot find temporaryFileClip
"); Case 6: die ("FileWrite failed
") ;}}?>

2:

Upload.html form:



You can directly run upload.html, such as http: // 127.0.0.1/WD/upload.html.

The page appears. Select the correspondingFileUpload will prompt


Note: The php page will have a size limit of more than 1 MB.


3:

Next, we need to use the libcurl libraryImplementationUpload.html form,ImplementationUpload function

Httpupload. h

# Ifndef COMMON_LINUX_HTTP_UPLOAD_H __# define COMMON_LINUX_HTTP_UPLOAD_H __# include# Include
  
   
Using std: map; class HTTPUpload {
   
Httpupload. cpp
# Include
    
     
# Include
     
      
# Include
      
       
# Include
       
        
# Include "stdafx. h "# include" HttpUpload. h "using namespace cocos2d; using namespace std; // Callback to get the response data from server. static size_t WriteCallback (void * ptr, size_t size, size_t nmemb, void * userp) {if (! Userp) return 0; string * response = reinterpret_cast
        
         
(Userp); size_t real_size = size * nmemb; response-> append (reinterpret_cast
         
           (Ptr), real_size); std: cout <response <endl; return real_size;} static const char kUserAgent [] = "Breakpad/1.0 (Linux )"; // staticbool HTTPUpload: SendRequest (const string & url, const map
          
            Meters, const string & upload_file, // "E: \ install.res.20.1.zip" const string & file_part_name, // "upload_file_minidump", const string & proxy, const string & proxy_user_pwd, const string & ca_certificate_file, string * response_body, long * response_code, string * error_description) {if (response_code! = NULL) * response_code = 0; if (! CheckParameters (parameters) return false; curl_global_init (CURL_GLOBAL_ALL); CURL * curl = curl_easy_init (); if (error_description! = NULL) * error_description = "No Error"; if (! Curl) {return false;} CURLcode err_code = CURLE_ OK; (curl_easy_setopt) (curl, CURLOPT_URL, url. c_str (); (curl_easy_setopt) (curl, CURLOPT_USERAGENT, kUserAgent); // Set proxy information if necessary. if (! Proxy. empty () (curl_easy_setopt) (curl, CURLOPT_PROXY, proxy. c_str (); if (! Proxy_user_pwd.empty () (curl_easy_setopt) (curl, CURLOPT_PROXYUSERPWD, proxy_user_pwd.c_str (); if (! Compile () (curl_easy_setopt) (curl, CURLOPT_CAINFO, ca_certificate_file.c_str (); struct curl_httppost * formpost = NULL; struct curl_httppost * lastptr = NULL; // Add form file. (curl_formadd) (& formpost, & lastptr, CURLFORM_COPYNAME, "file", CURLFORM_FILE, convert (), CURLFORM_END); (curl_easy_setopt) (curl, CURLOPT_HTTPPOST, formpost ); curl_formadd (& formpost, & lastptr, CURL FORM_COPYNAME, "submit", CURLFORM_COPYCONTENTS, "send", CURLFORM_END); // Disable 100-continue header. struct curl_slist * headerlist = NULL; char buf [] = "reverse CT:"; // struct curl_slist * (curl_slist_append) (struct curl_slist *, const char *); // * (void **) (& curl_slist_append) = dlsym (curl_lib, "curl_slist_append"); headerlist = (response) (headerlist, buf); (curl_easy_setopt) (curl, CURLOPT _ HTTPHEADER, headerlist); if (response_body! = NULL) {(curl_easy_setopt) (curl, CURLOPT_WRITEFUNCTION, WriteCallback); (curl_easy_setopt) (curl, CURLOPT_WRITEDATA, reinterpret_cast
           
             (Response_body);} // Fail if 400 + is returned from the web server. (curl_easy_setopt) (curl, CURLOPT_FAILONERROR, 1); err_code = (curl_easy_perform) (curl); if (response_code! = NULL) {(curl_easy_getinfo) (curl, CURLINFO_RESPONSE_CODE, response_code);} if (error_description! = NULL) * error_description = (curl_easy_strerror) (err_code); (curl_easy_cleanup) (curl); if (formpost! = NULL) {(curl_formfree) (formpost);} if (headerlist! = NULL) {(curl_slist_free_all) (headerlist);} // dlclose (curl_lib); return err_code = CURLE_ OK;} // staticbool HTTPUpload: CheckParameters (const map
            
              ¶ Meters) {for (map
             
               : Const_iterator pos = parameters. begin (); pos! = Parameters. end (); ++ pos) {const string & str = pos-> first; if (str. size () = 0) return false; // disallow empty parameter names for (unsigned int I = 0; I <str. size (); ++ I) {int c = str [I]; if (c <32 | c = '"' | c> 127) {return false ;}}return true;} // rewrite to read data into the upload data stream function size_t write_data (void * buffer, size_t size, size_t nmemb, void * userp) {FILE * fptr = (FILE *) userp; size_t m_size = fread (buffer, size, nmemb, fptr); return m_size ;}
             
            
           
          
         
        
       
      
     
    

To call the code below anywhere ImplementationSet E: \ 3.0.25.63.zip FileUpload to php ServerUnder the upload directory
CCLOG("################################################################################################ Begin send dump file");string strPath = "E:\\3.0.25.63.zip";std::map
    
      parameters;string response, error;const char * url = "http://127.0.0.1/WD/ReceiveFile.php";bool success = HTTPUpload::SendRequest(url,parameters,strPath.c_str(),//"upload_file_minidump","","","","",&response,NULL,&error);
    




The above code isSimpleThe demo code is quite rough, but it should not affect everyone's understanding. There is still a lot of room for optimization in the code. You can optimize and expand the space. We hope you can complete it together!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.