Search Unity

2 simple scripts to upload files to a http server and free hosting recommendation

Discussion in 'Assets and Asset Store' started by Deleted User, Jul 19, 2012.

  1. Deleted User

    Deleted User

    Guest

    hi there

    i made a couple of very simple scripts to upload files to a http server from unity, im using this approach to upload levels of a project im working on

    currently im testing them on a free web hosting account, at http://x10hosting.com/ which is great,ad free and with lots of space.. it has a few limitations like the requirement of logging in each month, but theres a couple of nice upgrades for the free plan or the premium which is a regular paid web hosting plan ..

    the scripts are relatively simple on line count so i will just paste them in here instead of attach them.

    first the script on the unity side, just modify some values like the urls and add it to a gameobject and thats it for a demo

    LevelUploader.cs

    Code (csharp):
    1.  
    2.  
    3. using UnityEngine;
    4. using System.Xml;
    5. using System.IO;
    6. using System.Collections;
    7. using System.Text;
    8.  
    9. // a very simplistic level upload and random name generator script
    10.  
    11. public class LevelUploader : MonoBehaviour
    12. {
    13.     void StartUpload()
    14.     {
    15.         StartCoroutine("UploadLevel");
    16.     }
    17.    
    18.     IEnumerator UploadLevel()  
    19.     {
    20.         //making a dummy xml level file
    21.         XmlDocument map = new XmlDocument();
    22.         map.LoadXml("<level></level>");
    23.        
    24.         //converting the xml to bytes to be ready for upload
    25.         byte[] levelData =Encoding.UTF8.GetBytes(map.OuterXml);
    26.        
    27.         //generate a long random file name , to avoid duplicates and overwriting
    28.         string fileName = Path.GetRandomFileName();
    29.         fileName = fileName.Substring(0,6);
    30.         fileName = fileName.ToUpper();
    31.         fileName = fileName + ".xml";
    32.        
    33.         //if you save the generated name, you can make people be able to retrieve the uploaded file, without the needs of listings
    34.         //just provide the level code name , and it will retrieve it just like a qrcode or something like that, please read below the method used to validate the upload,
    35.         //that same method is used to retrieve the just uploaded file, and validate it
    36.         //this method is similar to the one used by the popular game bike baron
    37.         //this method saves you from the hassle of making complex server side back ends which enlists available levels
    38.         //this way you could enlist outstanding levels just by posting the levels code on a blog or forum, this way its easier to share, without the need of user accounts or install procedures
    39.         WWWForm form = new WWWForm();
    40.  
    41.         print("form created ");
    42.        
    43.         form.AddField("action", "level upload");
    44.  
    45.         form.AddField("file","file");
    46.  
    47.         form.AddBinaryData ( "file", levelData, fileName,"text/xml");
    48.  
    49.         print("binary data added ");
    50.         //change the url to the url of the php file
    51.         WWW w = new WWW("http://www.yourdomainname.com/LevelUpload.php",form);
    52.         print("www created");
    53.  
    54.         yield return w;
    55.         print("after yield w");
    56.         if (w.error != null)
    57.         {
    58.             print("error");
    59.             print ( w.error );    
    60.         }
    61.         else
    62.         {
    63.             //this part validates the upload, by waiting 5 seconds then trying to retrieve it from the web
    64.             if(w.uploadProgress == 1  w.isDone)
    65.             {
    66.                 yield return new WaitForSeconds(5);
    67.                 //change the url to the url of the folder you want it the levels to be stored, the one you specified in the php file
    68.                 WWW w2 = new WWW("http://www.yourdomainname.com/Levels/" + fileName);
    69.                 yield return w2;
    70.                 if(w2.error != null)
    71.                 {
    72.                     print("error 2");
    73.                     print ( w2.error );  
    74.                 }
    75.                 else
    76.                 {
    77.                     //then if the retrieval was successful, validate its content to ensure the level file integrity is intact
    78.                     if(w2.text != null  w2.text != "")
    79.                     {
    80.                         if(w2.text.Contains("<level>")  w2.text.Contains("</level>"))
    81.                         {
    82.                             //and finally announce that everything went well
    83.                             print ( "Level File " + fileName + " Contents are: \n\n" + w2.text);
    84.                             print ( "Finished Uploading Level " + fileName);
    85.                         }
    86.                         else
    87.                         {
    88.                             print ( "Level File " + fileName + " is Invalid");
    89.                         }
    90.                     }
    91.                     else
    92.                     {
    93.                         print ( "Level File " + fileName + " is Empty");
    94.                     }
    95.                 }
    96.             }      
    97.         }
    98.     }
    99.    
    100.     void OnGUI()
    101.     {
    102.         if(GUILayout.Button("Click me!"))
    103.         {
    104.             StartUpload();
    105.         }
    106.     }
    107. }
    108.  
    109.  
    now the php script that will go in the http server, same just modify some info and thats it

    LevelUpload.php

    Code (csharp):
    1.  
    2.  
    3. <?php
    4. // a seriously minimalistic file upload script that you can build upon
    5.  
    6. //check if something its being sent to this script
    7. if ($_POST)
    8. {
    9.     //check if theres a field called action in the sent data
    10.     if ( isset ($_POST['action']) )
    11.     {
    12.         //if it indeed theres an field called action. check if its value its level upload
    13.         if($_POST['action'] === 'level upload')
    14.         {
    15.             //backwards compatible safe check for older php servers, http_post_files is deprecated on newer php servers    
    16.             if(!isset($_FILES)  isset($HTTP_POST_FILES))
    17.             {
    18.                 $_FILES = $HTTP_POST_FILES;
    19.             }//if
    20.                
    21.             //check if the field file which contains the binary data of the actual file uploaded successfully with no errors, the UPLOAD_ERR_OK means no error and upload was successful       
    22.             if ($_FILES['file']['error'] === UPLOAD_ERR_OK)
    23.             {
    24.                 //check if the file has a name, in this script it has to have a name to be stored, the file name is sent by unity
    25.                 if ($_FILES['file']['name'] !== "")
    26.                 {
    27.                     //this checks the file mime type, to filter the kind of files you want to accept, this script is configured to accept only xml files, you can edit this one and the unity side to allow your desired file      
    28.                     if ($_FILES['file']['type'] === 'text/xml')
    29.                     {
    30.                                
    31.                         //construct the final file name path, it depends on how your web hosting has things configured, if its x10 free hosting, just change username to your x10 hosting username
    32.                         //also you can change the levels folder to the name of the folder where you want to upload your files, the folder has to exist prior to using this script, or a error will occur
    33.                         // try using __FILE__ constant to find out what is the full path to this file,google more about it if you are not sure whats that about
    34.                         $uploadfile =  '/home/username/public_html/Levels/' . $_FILES['file']['name'];
    35.                        
    36.                         //once all safety checks are done, you can safely move the file from the temporary location to a public accessible location
    37.                         move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);              
    38.                     }//if
    39.                            
    40.                 }//if
    41.                    
    42.             }//if
    43.    
    44.         }//if
    45.        
    46.     }//if  
    47.    
    48. }//if
    49. ?>
    50.  
    51.  
    hope somebody finds this useful
     
  2. mrKaizen

    mrKaizen

    Joined:
    Feb 14, 2011
    Posts:
    139
    Tks for sharing -_^
     
  3. MaDDoX

    MaDDoX

    Joined:
    Nov 10, 2009
    Posts:
    764
    This is a great code sample, generally the hardest part is just get started, great that you clear it up for unity-php beginners :) Thanks!
     
  4. shaystibelman

    shaystibelman

    Joined:
    May 14, 2012
    Posts:
    3
    Hi,
    Thanks so much for sharing your code!
    I am pulling hairs trying to use (a different but does the same trick) code I've written in order to grab a screenshot taken from inside a webplayer and send it to myself via email using the exact same method you are talking about.

    The only thing is that I keep getting a 417 Expectation error, which from what I've heard, I'm supposed to fix using:
    System.Net.ServicePointManager.Expect100Continue = false;

    Funny thing - It doesn't.
    I've added it as a header: form.headers.Add("System.Net.ServicePointManager.Expect100Continue","false");
    But still nothing.
    Tried some other ways to add the header but I just keep getting the same error.

    I'd be so thankful for any suggestions you might think of!
     
  5. mgeorgoulopoulos

    mgeorgoulopoulos

    Joined:
    Aug 24, 2009
    Posts:
    66
    Thanks for this code, it works great for the free server you mentioned. However, the $_POST array on my server contains one element with all the fields inside, including some junk. May I mention that my server is apache based, if tha makes any difference.

    Any ideas?
    Cheers
     
  6. fondemzel

    fondemzel

    Joined:
    Sep 28, 2013
    Posts:
    2
    hermesdavidms,
    Thank you so much! Without your example I'd probably go loco with these phps/htmls stuff at this time.
     
  7. phime-studio

    phime-studio

    Joined:
    Nov 16, 2009
    Posts:
    49
    Thanx man! We modified it to suit our needs and it works flawlessly :)
     
  8. ParthbPatel86

    ParthbPatel86

    Joined:
    Sep 10, 2013
    Posts:
    1
    Ely-Prado likes this.
  9. li3ro

    li3ro

    Joined:
    Jul 11, 2015
    Posts:
    2
    any clue regarding managing the session vs the server? (client code will be sufficient)
     
  10. seanNovak

    seanNovak

    Joined:
    Aug 12, 2013
    Posts:
    12
    Thank you! Works great for me, modified to transfer png files.
     
  11. frankrs

    frankrs

    Joined:
    Aug 29, 2009
    Posts:
    300
    I just got immediate compile errors when importing the C# script
     
  12. rhylvin2016

    rhylvin2016

    Joined:
    Jul 14, 2016
    Posts:
    3
    how do you upload a file from unity to postman using Post? 3d file, image, audio, etc. not data but files.
     
  13. QuadMan

    QuadMan

    Joined:
    Apr 9, 2014
    Posts:
    122
    Having errors on 5.6. :(
     
  14. rodriguez80alvaro

    rodriguez80alvaro

    Joined:
    Oct 24, 2017
    Posts:
    2
    Hi the version is very good, Funny thing - It doesn't.
    I've added it as a header: form.headers.Add("System.Net.ServicePointManager.Expect100Continue","false");
    But still nothing.
    Tried some other ways to add the header but I just keep getting the same error. example: https://www.zz.com.ve/en/offer/vps

    I'd be so thankful for any suggestions you might think of!
     
  15. Goatbuoy

    Goatbuoy

    Joined:
    Sep 29, 2016
    Posts:
    1
    I've just used this 6 years later and all I had to do is add some OR bars (||) - thank you very much for sharing!
     
  16. guneyozsan

    guneyozsan

    Joined:
    Feb 1, 2012
    Posts:
    99
    Yep, 6 years and still has value. Thanks!
    If you want you can validate the file by comparing bytes:
    if (string.Equals(Convert.ToBase64String(levelData), Convert.ToBase64String(w2.bytes)))
     
  17. junedmmn

    junedmmn

    Joined:
    Dec 19, 2016
    Posts:
    15
    The code is not working, on inifinityfree webhosting I am getting Forbidden error, and on 000webhost I am getting Not found error. I am new to PHP, please help.
     
  18. mrekuc

    mrekuc

    Joined:
    Apr 17, 2009
    Posts:
    116
    It's missing the || on line 16

    Other then that it works!

    if(!isset($_FILES) isset($HTTP_POST_FILES))
    if(!isset($_FILES) || isset($HTTP_POST_FILES))
     
    Marc-Saubion likes this.
  19. DevMaxima

    DevMaxima

    Joined:
    Jan 24, 2017
    Posts:
    5
    thanks, I see this works, just add in if condition or "||" ..

    how If I want upload other file like .zip or .obj?