繁体   English   中英

无法使用PaperClip将图像从Android上传到Rails服务器

[英]Trouble Uploading Image from Android to Rails Server Using 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。 我正在使用paperclip gem。

谢谢!

这就是我解决的问题。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM