Search code examples
uploadwebservertitaniumappcelerator

Titanium Appcelerator uploading images to webserver


I am having a lot of issues trying to upload files to the server in Titanium appcelerator. All seems to work fine, but in the server it shows that an error has occurred. Here's my Titanium code:

 var win = Ti.UI.createWindow({

backgroundColor : "#FFF"
});


 var ind = Titanium.UI.createProgressBar({
width : 200,
height : 50,
min : 0,
max : 1,
value : 0,
style : Titanium.UI.iPhone.ProgressBarStyle.PLAIN,
top : 10,
message : 'Uploading Image',
font : {
    fontSize : 12,
    fontWeight : 'bold'
},
color : '#888'
  });

  win.add(ind);
  ind.show();

   win.open();

      Titanium.Media.openPhotoGallery({

success : function(event) {
    alert("success! event: " + JSON.stringify(event));
    var image = event.media;

    var xhr = Titanium.Network.createHTTPClient();

    xhr.onerror = function(e) {
        Ti.API.info('IN ERROR ' + e.error);
    };
    xhr.onload = function() {
        Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
    };
    xhr.onsendstream = function(e) {
        ind.value = e.progress;
        //Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress + ' ' + this.status + ' ' + this.readyState);
    };
    // open the client
    xhr.open('POST', 'http://mypathtotheserver/myphpuploaderfile.php');
    xhr.setRequestHeader("Connection", "close");
    // send the data
    xhr.send({
        media : image
    });

},
cancel : function() {

},
error : function(error) {
},
allowImageEditing : true

});

and the php code in the server:

  $target_path = "uploads/";

 $target_path = $target_path .  $_FILES['media']['name']; 

 if(move_uploaded_file($_FILES['media']['tmp_name'],$target_path)) {
    echo "The file ".  basename( $_FILES['media']['name']). 
    " has been uploaded";
  } 
  else
 {
  echo "There was an error uploading the file, please try again!";
 }

What am I doing wrong? Any help is highly appreciated.

Thank you in advance!


Solution

  • Well after spending a long time trying to get this to work, I finally found the correct answer. I will share here for anyone out there running into issues to take a look and fix the photo upload problem. I haven't tested using Android yet, but it should all work the same.

    Here's the titanium 'app.js' code:

        var win = Ti.UI.createWindow({
    
             backgroundColor : "#FFF"
        });
    
        var ind = Titanium.UI.createProgressBar({
            width : 200,
            height : 50,
            min : 0,
            max : 1,
            value : 0,
            style : Titanium.UI.iPhone.ProgressBarStyle.PLAIN,
            top : 10,
            message : 'Uploading Image',
            font : {
            fontSize : 12,
            fontWeight : 'bold'
           },
             color : '#888'
          });
    
        win.add(ind);
        ind.show();
    
        win.open();
    
         //Not a necessary function, but just in case you want to randomly create names
         // for each photo to be uploaded
        function randomString(length, current) {
            current = current ? current : '';
            return length ? randomString(--length, "abcdefghiklmnopqrstuvwxyz".charAt(Math.floor(Math.random() * 60)) + current) : current;
        }
    
    Titanium.Media.openPhotoGallery({
    
    success : function(event) {
    
        var image = event.media;
    
        var xhr = Titanium.Network.createHTTPClient();
    
        xhr.open('POST', 'http://yoursite.com/scriptsfolder/upload.php');
    
        xhr.onerror = function(e) {
            Ti.API.info('IN ERROR ' + e.error);
        };
        xhr.onload = function(response) {
    
             if ( this.responseText !=0){
                var imageURL = this.responseText;
                alert('Your image was uploaded to ' +imageURL);
             }else {
    
                 alert("The upload did not work! Check your PHP server settings.");
             }
    
        };
        xhr.onsendstream = function(e) {
            ind.value = e.progress;
    
        };
    
          // send the data
           var r = randomString(5) + '.jpg';
          xhr.send({
            'media': image,
            'randomFilename' : r
          });
    
        },
        cancel : function() {
    
        },
        error : function(error) {
       },
         allowImageEditing : true
        });
    

    And here is the PHP server-side script. You will need to upload this PHP file to your webserver:

        <?php
    
          $target = getcwd();
          $target = $target .'/'. $_POST['randomFilename'];
    
    
          if (move_uploaded_file($_FILES['media']['tmp_name'], $target)) {
    
          $filename = $target;
    
        //Get dimensions of the original image
    
          list($current_width, $current_height) = getimagesize($filename);
    
        // The x and y coordinates on the original image where we  will begin cropping the image
        $left = 0;
        $top  = 0;
    
        //This will be the final size of the image (e.g how many pixesl left and down we will be doing)
        $crop_width = $current_width;
        $crop_height = $current_height;
    
        //Resample the image
        $canvas = imagecreatetruecolor($crop_width, $crop_height);
        $current_image = imagecreatefromjpeg($filename);
        imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
        imagejpeg($canvas, $filename, 100);
    
        echo 'http://yoursite.com/scriptsfolder/'.$_POST['randomFilename'];
    
           }else {
    
            echo "0";
            }
    
        ?>
    

    And there you have it. I have to say that I found the answer to this problem from boydlee's appcelerator cookbook.

    I hope this helps someone who is struggling to get photo upload to their own webserver in Titanium.

    Thanks!