6

我正在尝试将图像从 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。我正在使用回形针宝石。

谢谢!

4

1 回答 1

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 令牌。

于 2012-12-12T08:57:38.930 回答