Search code examples
httptitanium

upload image with data to server Titanium


i have some data i need to upload it to the server with an image using

multipart/form-data    

but i getting request time out this is my data

  var data={
       property_name:p_n_txt.value,
       friendly_name:f_txt.value,
       property_type:clicked,
       size:space_Slider.getValue(),
       price:price_Slider.getValue(),
       number_of_bedrooms:bedrooms_Slider.getValue(),
       number_of_bathrooms:bathrooms_Slider.getValue(),
       number_of_parkings:p_space_Slider.getValue(),
       location:a_txt.value,
       features:13,
       payment_method:4,
       image1_name:"image0.png",
       image1:Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory,Ti.App.Properties.getString("filename")),

   };    

and the httpclient is

var xhr = Ti.Network.createHTTPClient({
    onload: function() {
    var myData = JSON.parse(this.responseText);
    console.log(this.responseText);


    },
    // function called when an error occurs, including a timeout
    onerror : function(e) {
    Ti.API.debug(e.error);
    console.log(this.status);
    console.log(e.error);

    },
    timeout : 20000
    });

    xhr.open('POST','http://url/');
    xhr.setRequestHeader("enctype", "multipart/form-data");
     xhr.setRequestHeader("Content-Type", "image/png");
     // xhr.setRequestHeader("Content-Type", "image/jpeg");

    xhr.send(data);


});   

here is should form data not a json so there is no need to add json.stringify

but i have 4 cases i tried with them

first :with stringify i got HTTP 415 if i added contentType "image/png"
and HTTP 500 if i didn't added
second without stringify when i add added contentType "image/png" i got request time out
and when i didn't add it i get HTTP 413
any idea on how to accomplish this cause i found many question about it but no one was helpful for me
thanks


Solution

  • Why don't you try with encoding your image as base64encoded and pass it on and at the server end just decode it and you would be go enough to proceed.

    Ti.Utils.base64encode(image.toBlob()).toString();
    

    This can be sent to server and no headers would be required to sent.