Upload a File to a Remote Server with PhoneGap
March 26, 2011
I recently started looking at PhoneGap as a way to build native smartphone applications without having to learn another programming language. The process, so far, has been going very well. I've been able to build a basic application with very little trouble. I did, however, hit a big hiccup in development when I decided to try and upload a file from a phone to a remote location. The unfortunate part of this hiccup was that I think its primary cause is rooted in poor documentation.
In this post, I want to explain how I was able to upload a photo from a phone, using PhoneGap (and PHP on the remote server), to a remote server. I am going to assume that you have some knowledge of PhoneGap and already have a method, either the Android SDK or the iPhone SDK, to test your native application.
Rather then use a jQuery Ajax call, I am relying on PhoneGap's FileTransfer object to post the image to a remote server. The code below is all you need to add to your "index.html" PhoneGap file for a basic upload. Make sure, if you use the example code below, to add your server's URL in the appropriately marked place.
As you can see, the code above allows you to browse for a photo in the device's photo library using the function
getImage(). Once a photo is chosen, it gets POSTed as multi-part data to the server. You will notice that you can include some test parameters in the upload data which will be POSTed to your server as well, but these are optional. One very important piece of information discovered by other PhoneGap developers (thank you Ryan and Jeff) is that this script doesn't work until you add "options.chunkedMode = false;" to the code. If you don't append this line of code, data won't be readable by your PHP server.
Now that you are able to find a file and upload it to a server, you'll need a server side script to handle the data. Here is a very basic PHP example on handling the multi-part form data (image) that was just sent from the device.
The above code uses PHP's
move_uploaded_file() to move the uploaded file from a temporary location to a new directory. To make sure it works, change "/srv/www/upload/" to a directory on your server. I usually have to pass an absolute file-path as the second variable in the
move_uploaded_file() for it to work. You can learn more about PHP uploads in a previous post of mine.
If you are developing on an Android device, you can download an example Eclipse project for PhoneGap 1.5.0.