Monday, May 28, 2012

Appcelerator - HTTP Post Image To Server

Appcelerator HTTPClient provide quite a easy way to perform HTTP POST to server.  The following code perform a simple POST to a remote server

var postUrl "http://host:port/posturl";var data = {
    name: "John",
    age: "11"
var httpClient = Titanium.Network.createHTTPClient({
    timeout : 60000});'POST', postUrl);

The trick is create a data variable with {key:value} pair and open a POST http client. Appcelerator will understand the value pair and send http POST to your URL stated in postUrl.

The data arrive in the server will be in standard multipart POST message as follows

Content-Disposition: form-data; name="name"


It can also perform HTTP POST raw image bytes to remote server. However, on my testing, there are something wrong with the raw bytes. The raw bytes size arrived at server doubled compares to the original bytes. I am not sure what is the reason, So, if you encounter this issue whereby your server does not understand the posted bytes, here is the alternative solution.

var postUrl =  "http://host:port/posturl";var data {
    name: "John",
    age: "11",
    picture: Ti.Utils.base64encode(image)
var httpClient Titanium.Network.createHTTPClient({
    timeout : 60000});'POST', postUrl);

The basic idea is to base64 encode the raw bytes and post to the server

picture: Ti.Utils.base64encode(image)

In the above line, image is a TiBlob and its contents is encoded by base64.

An example of the image POST data is

Content-Disposition: form-data; name="picture"; filename="1h39ae13.bin"
Content-Type: application/octet-stream

 ... BASE64 Encoded Image Bytes

On the server, you have to Base64 decode the image post string and convert it to byte[].

No comments:

Post a Comment

Bootstrap Validator - Submit button remain disabled even when form is valid

If you work with Boostrap Validator (, you may experience an issue when your entire form is ...