Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble Uploading Image from Android to Rails Server Using PaperClip

Tags:

android

ruby

I'm trying to upload images to my rails server from Android. All my other data uploads, but I get a "Error invalid body size" error. It has to do with the image. Below is my code. Help?!

 public void post(String url) {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("content_type","image/jpeg");
            try {
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                entity.addPart("picture_file_name", new StringBody("damage.jpg"));
                File file = new File((imageUri.toString()));
                entity.addPart("picture", new FileBody(file, "image/jpeg"));
                httpPost.setEntity(entity);         
                HttpResponse response = httpClient.execute(httpPost, localContext);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

I've tried removing the browser compatible parameter, but it doesn't help. my image is being stored as an URI called imageUri. I'm using paperclip gem.

thanks!

like image 268
Jason van der Merwe Avatar asked Jul 12 '12 18:07

Jason van der Merwe


1 Answers

This is how I solved.

MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (NameValuePair nameValuePair : nameValuePairs) {
        if (nameValuePair.getName().equalsIgnoreCase("picture")) {
                File imgFile = new File(nameValuePair.getValue());
                FileBody fileBody = new FileBody(imgFile, "image/jpeg");
                multipartEntity.addPart("post[picture]", fileBody);
        } else {
                multipartEntity.addPart("post[" + nameValuePair.getName() + "]", new StringBody(nameValuePair.getValue()));
        }                   
    }
httpPost.setEntity(multipartEntity);
HttpResponse response = httpClient.execute(httpPost, httpContext);

This will produce a POST like this:

{"post"=>{"description"=>"fhgg", "picture"=>#<ActionDispatch::Http::UploadedFile:0x00000004a6de08 @original_filename="IMG_20121211_174721.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"post[picture]\"; filename=\"IMG_20121211_174721.jpg\"\r\nContent-Type: image/jpeg\r\nContent-Transfer-Encoding: binary\r\n", @tempfile=#<File:/tmp/RackMultipart20121211-7101-3vq9wh>>}}

In the rails application your model attributes must have the same name you use in your request , so in my case

class Post < ActiveRecord::Base
  attr_accessible :description, :user_id, :picture

  has_attached_file :picture # Paperclip stuff
...
end

I have also disabled the CSRF token from the rails application.

like image 187
Pietro Avatar answered Sep 19 '22 00:09

Pietro