2012-07-12 5 views
6

Android에서 내 레일 서버로 이미지를 업로드하려고합니다. 내 모든 다른 데이터가 업로드되지만 "잘못된 바디 크기 오류"오류가 발생합니다. 그것은 이미지와 관련이 있습니다. 아래는 제 코드입니다. 도움?!PaperClip을 사용하여 Android에서 Rails로 이미지 업로드 문제

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(); 
      } 
     } 

브라우저 호환 매개 변수 제거를 시도했지만 도움이되지 않습니다. 내 이미지가 imageUri라는 URI로 저장됩니다. 나는 클립 클립 보석을 사용하고 있습니다.

감사합니다.

답변

6

이것은 내가 어떻게 해결했는지입니다.

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); 

이이 같은 POST 생산합니다 : 모델은 내 경우에는, 그래서 당신은 당신의 요구 에서 사용하는 것과 동일한 이름을 가져야합니다 속성 레일 응용 프로그램에서

{"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>>}} 

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

    has_attached_file :picture # Paperclip stuff 
... 
end 

또한 레일스 애플리케이션에서 CSRF 토큰을 비활성화했습니다.

관련 문제