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

Comments

Popular Posts