Thursday, June 30, 2011

Upload a File to a Remote Server with Phonegap

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.

The HTML / Javascript 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 getPhoto(). Once a photo is chosen, it gets POSTed as multi-part data to the server.

You will notice a couple of things. 1. I commented out the options.fileName variable. The default name for an uploaded image is “image.jpg.” Also, I’ve included some test parameters in the upload data which will be POSTed to your server as well, but these are optional.

The PHP Now that you are able to find a file and POST 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. Finished Above is a short example of how to upload a file to a remote server using PhoneGap, including how to handle that data once it gets to the server.

No comments:

Post a Comment