2012-07-12 144 views
6

我試圖從Android上傳圖像到我的Rails服務器。我所有的其他數據上傳,但我得到一個「錯誤無效的身體大小」錯誤。它與形象有關。以下是我的代碼。幫幫我?!使用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>>}} 

在Rails應用程序的模型屬性必須有您在請求 使用相同的名稱,所以在我的情況

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

    has_attached_file :picture # Paperclip stuff 
... 
end 

我也禁用了rails應用程序中的CSRF令牌。

相關問題