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[].

1 comment:

  1. ldap online training| ldap training| call us+919000444287 ...
    LDAP Online Training, LDAP training, LDAP course contents, LDAP , call us: +919000444287,


Facebook - Control privacy setting of liked page

By default, Facebook displayed your liked page to public. It is the user responsibility to adjust the privacy setting. And in my opinion, F...