Problems uploading an image from Android to a Rails server using PaperClip

I am trying to upload images to my rails server from Android. All my other data is loading, but I get the error "Invalid body size error." This is due to 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 tried to remove the browser compatible option, but that will not help. my image is stored as a URI called imageUri. I use a paperclip gem.

thanks!

+6
source share
1 answer

This is how I decided.

 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 result in a POST as follows:

 {"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 should have the same name that 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 also disabled the CSRF token from the rails application.

+6
source

Source: https://habr.com/ru/post/920355/


All Articles