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});
httpClient.open('POST', postUrl);
httpClient.send(data);



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

--0xKhTmLbOuNdArY-11C2E750-7BF3-444E-AC7F-AAEAB534613F
Content-Disposition: form-data; name="name"

John
--0xKhTmLbOuNdArY-11C2E750-7BF3-444E-AC7F-AAEAB534613F--





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});
httpClient.open('POST', postUrl);
httpClient.send(data);


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


--0xKhTmLbOuNdArY-11C2E750-7BF3-444E-AC7F-AAEAB534613F
Content-Disposition: form-data; name="picture"; filename="1h39ae13.bin"
Content-Type: application/octet-stream

 ... BASE64 Encoded Image Bytes
 --0xKhTmLbOuNdArY-11C2E750-7BF3-444E-AC7F-AAEAB534613F

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

1 comment:

  1. ldap online training| ldap training| call us+919000444287 ...
    www.21cssindia.com/courses/ldap-online-training-103.html
    LDAP Online Training, LDAP training, LDAP course contents, LDAP , call us: +919000444287,dharani@21cssindia.com.

    ReplyDelete

Hadoop - How to setup a Hadoop Cluster

Below is a step-by-step guide which I had used to setup a Hadoop Cluster Scenario 3 VMs involved: 1) NameNode, ResourceManager - Host...