Jason van der Merwe
Jason van der Merwe

Reputation: 299

Trouble Uploading Image from Android to Rails Server Using PaperClip

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!

Upvotes: 6

Views: 2313

Answers (1)

Pietro
Pietro

Reputation: 332

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.

Upvotes: 6

Related Questions