15 August 2006 · About 4 minutes read

J2ME Uploading Images to PHP Script

8 March 2011 Kutay Ozdogru has posted a recent, complete example of how to upload images via J2ME to PHP on the Nokia forums.

I’ve posted this as a helpful pointer to those looking into J2ME server interaction, and as a reminder to myself when I am next trying to figure out uploading J2ME images to PHP.

Something that constantly eluded me through the development of Toupix was an elegant way to get images from a phone to the server. Due to deadlines, I eventually decided to submit the image as an email and use PHP’s IMAP functionality to read and decode the email. Whilst functional, this wasn’t exactly the solution to end all solutions.

What frustrated me the most is that this should be something relatively simple, yet days and days of frustrating research and playing around with various encoding algorithms still resulted in invalid images being saved. The data was being received by the script, but something was getting garbled.

So, finally, I have discovered the solution - and it’s incredibly simple. Browsing forums, it is clear that the image data needs to be encoded into a Base64 string, and Stefan Haustein’s Base64 class provides the ideal method for doing this. Using Base64.encode(), the raw byte array of an image is returned as Base64 string.

```java public static boolean uploadImage( String uri, byte[] rawImage, String filename )

throws Exception

{

HttpConnectionhttpConnection;

OutputStream out;

// Open connection to the script

httpConnection = (HttpConnection)Connector.open( uri );

// Setup the request as an HTTP POST and encode with form data

httpConnection.setRequestMethod( HttpConnection.POST );

httpConnection.setRequestProperty( “Content-type”, “application/x-www-form-urlencoded” );

// Encode the imagedata with Base64

String encoded = Base64.encode( rawImage ).toString();

// Build the output and encoded string

String output = “file=” + filename + “&imgdata=” + encoded;

// Set the content length header

httpConnection.setRequestProperty(“Content-Length”, Integer.toString((output.getBytes().length)));

// Open the output stream and publish data

out = httpConnection.openOutputStream();

out.write( output.getBytes() );

// Flush the buffer (might not be necessary?)

out.flush();

// Here you might want to read a response from the POST to make

// sure everything went OK.

// Close everything down

if( out != null )

if( httpConnection != null )

httpConnection.close();

// All good

return true;

}```

The next step is to get this string published to the server (PHP script). This is where the problems started. Most documentation I found assumed we are uploading to a JSP script, and there is little mention of PHP. The easiest way to get our data to PHP is via HTTP POST, and since our image is now a normal string, we can happily POST it to the server. The PHP script on the server can then read the string via the normal $_POST[] variable, and (theoretically) decode it:

```php…

//Decode the image from Base64 encoding

$img= base64_decode( $data );

//Write out data to file

if( $fp = fopen( $out, ‘wb’ ) )

{

//Write data to the file

fwrite( $fp, $img );

//Close the file

fclose( $fp );

}

else

{

die( “Error writing to image file $out” );

}

…```

Unfortunately, though, something seems to happen to the data when it arrives on our server. It is at this point that everything was going wrong; the data was corrupt by the time it was decoded, and thus the image file produced was invalid. It turns out (and it had to be so simple) that we need to strip the Base64 string of spaces, and replace them with a + character!

```phpfunction stripLineBreaks( $encode )

{

$data= str_replace( ‘ ‘, ‘+’, $encode );

//$data= str_replace( ‘rn’, ‘’, $data );

return $data;

}```

Now, before decoding the base64 string, just run it through this function first:

```php…

//Decode the image from Base64 encoding

$data= stripLineBreaks( $data );

$img= base64_decode( $data );

//Write out data to file

…```

At last, an image uploaded to your server via a J2ME MIDlet (under emulation - I’m using the Sony WTK set to use HTTP1.0). There are likely to be issues running it on a phone or emulator under HTTP1.1. My server doesn’t handle chunked data, which HTTP1.1 enforces by breaking the sent image data into chunks. This forum post shows a possible way around this, and if I find a successful method I’ll be sure to post it!

Was this post useful? Please leave me your comments and feedback.

Chris Blunt
Chris Blunt @cblunt
Chris is the founder of Plymouth Software. As well as code and business, he enjoys being a Dad, swimming, and the fine art of drinking tea.