使用PaperClip将图像从Android上传到Rails服务器
问题描述:
我试图从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。我使用回形针宝石。
谢谢!
答
这就是我解决问题的方法。
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令牌。