Uploading image via Post method for rails server with paperclip plugin

Viewed 2940

I have a rails app with a controller called matches with the create method:

def create
@match = Match.new(params[:match])
respond_to do |format|
  if @match.save
    #do stuff here
  end
end

and this is my model

class Match < ActiveRecord::Base
  attr_protected
  has_attached_file :pic, :styles => { :medium => "500x500>"}
end

I want to be able to use this rails server so that my android phone would be able to upload images to this server. I tried several code examples for this but I could not get it to work.

Any idea on how I can write a method to do the post method call to upload the image?

If there are any resources that can help me with this, Can you please guide me to it?

*EDIT***

Here's the code I tried earlier

public void callPost()
{
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://192.168.1.7:3000/matches");
    MultipartEntityBuilder build = MultipartEntityBuilder.create();
    File file = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath()+"/test.jpg");

    build.addPart("pic", new FileBody(file));

    HttpEntity ent = build.build();
    post.setEntity(ent);
    HttpResponse resp = null;
    try
    {
        resp = client.execute(post);
        HttpEntity resEnt = resp.getEntity();
        String result = EntityUtils.toString(resEnt);
        tv.setText(result);
    }
    catch(Exception e)
    {
        tv.setText("error");
        e.printStackTrace();
    }

}

This is a code I tried to test if I could get the POST method working.

This code sent the image as a binary data stream(I think) so I had this error on my server logs:

Parameters: {"match"=>{"pic"=>"\xFF\xD8\xFF\xE1a\xDFExif\u0000\u0000MM\u0000*\u0000\u0000\u0000\b\u0000\b\u0001\u000F\u0000\u0002\u0000\u0000\u0000\u0004LGE\u0000\u0001\u0010\u0000\u0002\u0000\u0000\u0000\b\u0000\u0000\u0000n\u0001\u001A\u0000\u0005\u0000\u0000\u0000\u0001\u0000\u0000\u0000v\u0001\e\u0000\u0005\u0000\u0000\u0000\u0001\u0000\u0000\u0000~\u0


//Tonnes more of this


\xE3?\x86+9l\r\xB4\x81o\"\xB6բ{\xD5+\u0003\xB1\u0001\x87+\x91\xF8t\xCF\xF5\xAB^ \xD0භ\x91\xE0\x84\xCD\f\xAD\x8D\xFB\xF8C\xD7\u0018\xFC\xEB6IR\xF2\xD7̒S\u001Eᔄ(\vK\xA5\x82\xE17yN\xA3\xEE\xF5\xE7\u07B4\xBC5%\x96\xAFnЉ\t\u000Ex|g\a\xE9\xFD>\xB5.\xB9\xA0\xE8\xDA%\xB0\xBF\x96\u0004\x9E\xE4.\u0016\xE0\f\x98c\xC8\xC9\xFA\u001Er}\xA9\x8A\xD7G\xFF\xD9"}}
Completed 500 Internal Server Error in 1ms
2 Answers
Related