Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

How to Select and upload image by

Hi all.

A question on Android enviroment.

I want to choose and upload an image, selected from gallery, by an html "input type file form" in one webview.

Below the simple html code

index.html

<form action="http://www.example.com/upload" method="post"
 enctype="multipart/form-data">
<p>select image:<input type="file" name="image"
 onclick='send("select_button");return false;'></p>

<p><input type="submit" name="Submit" 
value="Search now!" /></p>
</form>

<script>
    function send(event) {
    Ti.App.fireEvent(event);
}
</script>

app.js

var image;

Ti.App.addEventListener('select_button', function()
{
    Titanium.Media.openPhotoGallery({

        success:function(event)
        {
            image = event.media;
        },
        cancel:function(){},
        error:function(){},
        allowImageEditing:true
    });
});

The image selection works great but how can i pass the selected imagepath to the submit form and post it?

Anyone can help me?

Thanx and regards

ps. sorry for my english ;)

— asked October 25th 2010 by Francesco Soccolini
  • android
  • events
  • fire
  • html
  • image
  • upload
  • webview
0 Comments

3 Answers

  • Hi Francesco,

    You would not use an HTML form to POST an image in this case. Once you have a handle on the file, you would upload it via our HTTPClient object, as in:

    var xhr = Titanium.Network.createHTTPClient();
    xhr.onload = function() {
        //one of...
        var doc = this.responseXML.documentElement;
        //or this, for JSON...  var json = JSON.parse(this.responseText);
        //do stuff with response
    };
    xhr.open('POST','http://yourserver.com/upload');
    xhr.send({
        media:image,
        someOtherPOSTparam:'somevalue'
    });
    
    — answered October 25th 2010 by Kevin Whinnery
    permalink
    1 Comment
    • Hi. Thanks for the answer.

      Now i use xhr ( as suggest ), but when i try to send data to server i catch this java exception:

      Error evaluating source: Wrapped java.lang.NullPointerException

      Seems like apps doesn't find the image file, previously selected ( view code above ).

      Any tips?

      Regards.

      — commented October 26th 2010 by Francesco Soccolini
  • Hi. Thanks for the answer.

    Now i use xhr ( as suggest ), but when i try to send data to server i catch this java exception:

    Error evaluating source: Wrapped java.lang.NullPointerException

    Seems like apps doesn't find the image file, previously selected ( view code above ).

    Any tips?

    Regards.

    — answered October 26th 2010 by Francesco Soccolini
    permalink
    0 Comments
  • Hi,
    I would like to further ask Kevin Whinnery when he mentioned to get the 'handle on the file', what do you mean by that? I am in a similar scenario where I want to build a webapp that create a post (title/content + picture) to my ACS account. Title and content have no issue. The issue I have is the photo field. I tried to get the data from the form once the user has selected the picture file from the browse menu, it turns out that the file path is something like 'c:/fakePath/filename.jpg', I tried removing the 'fakepath' string, hardcoding the actual path of the file \Desktop\filename.jpg, adding '@' as a prefix (like in curl script), and many combinations. Nothing seems to work and I cannot get the picture to save on ACS, the title/content text did get posted though.

    I am following the JS SDK as written here: http://cloud.appcelerator.com/docs/api/v1/posts/create

    Would be grateful for anyone who can help!

    Here is the code snippet I have

        var data = {
            title: "Have you watched the Olympics closing ceremony?",
            content: "it was pretty awesome!",
            photo: "\Users\mickeymouse\Desktop\rising_sun_japans_05.jpg"
        };
    
        sdk.sendRequest('posts/create.json', 'POST', data, function(data) {
            if(data) {
                if(data.meta) {
                    var meta = data.meta;
                    console.log(data);
                    if(meta.status == 'ok' && meta.code == 200 && meta.method_name == 'createPost') {
                        var posts = data.response.posts;
                        console.log(posts);
                    } else console.log('something wrong with meta.status: createTopic');
                } else console.log('something wrong with data.meta: createTopic');
            } else console.log('something wrong with data: createTopic');
        });
    

    Thanks much,
    Kavin

    — answered August 14th 2012 by Mickey Asavanant
    permalink
    2 Comments
    • I am trying to make the curl_exec() work at the moment.
      I set &photo=@/User/XXXX/images/dolphin.jpg and it is giving me the following error:

      Array ( [meta] => Array ( [status] => fail [code] => 400 [message] => Failed to upload photo: Failed to indentify photo file [method_name] => updatePlace ) )

      I do make sure that the image exists and accessible.

      — commented March 11th 2013 by Snapp Coupon
    • Precisely… I'm getting the Same Error from a simple HTML Upload Image to ACS:

      <!doctype html>
      <html>
      <head>
          <meta charset="utf-8">
      
          <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
      <script type="text/javascript" src="http://sdk.cocoafish.com/js/cocoafish-1.2.min.js"></script>
      
      <script type="text/javascript">
      
      $(document).ready(function() {
      
          $('#submit').click(function() {
              var input = $("#imagefile");
              console.log(input[0].files)
                      if (input[0].files && input[0].files[0]) {
                      var reader = new FileReader();
                      console.log(input[0].files[0].name);
                      reader.onload = function (e) {
                          console.log(e.target.result);
      
                          $('#errorMsg').show();
                          $('#blah').attr('src', e.target.result);
                      var sdk = new Cocoafish('XXXXXX'); // please replace
      
                           sdk.sendRequest('photos/create.json', 'POST',{photo:e.target.result}, function(responseData) {
                              console.log('ACS response ' + responseData.meta.code + ' ' + responseData.meta.message);
                           });
      
                      }
                      reader.readAsDataURL(input[0].files[0]);
                  }
      
          });
      });
      </script>
      </head>
      
      <body>
       <form action="javascript:void(0)" method="POST" class='form-horizontal form-validate' id="aaa" enctype="multipart/form-data" runat="server">
              <input type='file' id="imagefile"  />
              <img id="blah" src="#" alt="your image" />
              <input type="submit" value="Submit" id="submit" name="submit" class='btn btn-primary'>
          </form>
      </body>
      </html>
      

      Anybody found a Solution?

      — commented June 4th 2013 by Joseph Sachs
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.