繁体   English   中英

使用paperclip插件通过Post方法为rails服务器上传图像

[英]Uploading image via Post method for rails server with paperclip plugin

我有一个带有控制器的rails应用程序,与create方法匹配:

def create
@match = Match.new(params[:match])
respond_to do |format|
  if @match.save
    #do stuff here
  end
end

这是我的模特

class Match < ActiveRecord::Base
  attr_protected
  has_attached_file :pic, :styles => { :medium => "500x500>"}
end

我希望能够使用这个rails服务器,以便我的Android手机能够将图像上传到此服务器。 我尝试了几个代码示例,但我无法让它工作。

有关如何编写方法来执行post方法调用以上传图像的任何想法?

如果有任何资源可以帮助我,请你指导我吗?

* 编辑 * **

这是我之前尝试过的代码

public void callPost()
{
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://192.168.1.7:3000/matches");
    MultipartEntityBuilder build = MultipartEntityBuilder.create();
    File file = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath()+"/test.jpg");

    build.addPart("pic", new FileBody(file));

    HttpEntity ent = build.build();
    post.setEntity(ent);
    HttpResponse resp = null;
    try
    {
        resp = client.execute(post);
        HttpEntity resEnt = resp.getEntity();
        String result = EntityUtils.toString(resEnt);
        tv.setText(result);
    }
    catch(Exception e)
    {
        tv.setText("error");
        e.printStackTrace();
    }

}

这是我尝试测试的代码,如果我可以使POST方法工作。

此代码将图像作为二进制数据流发送(我认为),因此我在服务器日志中出现此错误:

Parameters: {"match"=>{"pic"=>"\xFF\xD8\xFF\xE1a\xDFExif\u0000\u0000MM\u0000*\u0000\u0000\u0000\b\u0000\b\u0001\u000F\u0000\u0002\u0000\u0000\u0000\u0004LGE\u0000\u0001\u0010\u0000\u0002\u0000\u0000\u0000\b\u0000\u0000\u0000n\u0001\u001A\u0000\u0005\u0000\u0000\u0000\u0001\u0000\u0000\u0000v\u0001\e\u0000\u0005\u0000\u0000\u0000\u0001\u0000\u0000\u0000~\u0


//Tonnes more of this


\xE3?\x86+9l\r\xB4\x81o\"\xB6բ{\xD5+\u0003\xB1\u0001\x87+\x91\xF8t\xCF\xF5\xAB^ \xD0භ\x91\xE0\x84\xCD\f\xAD\x8D\xFB\xF8C\xD7\u0018\xFC\xEB6IR\xF2\xD7̒S\u001Eᔄ(\vK\xA5\x82\xE17yN\xA3\xEE\xF5\xE7\u07B4\xBC5%\x96\xAFnЉ\t\u000Ex|g\a\xE9\xFD>\xB5.\xB9\xA0\xE8\xDA%\xB0\xBF\x96\u0004\x9E\xE4.\u0016\xE0\f\x98c\xC8\xC9\xFA\u001Er}\xA9\x8A\xD7G\xFF\xD9"}}
Completed 500 Internal Server Error in 1ms

我会为你解释一下这个问题:


JSON

Android可能会通过JSON / Ajax将映像发送到Rails。 虽然我在代码中看不到这一点,但它是典型的工作方式( REST API

您显示的params错误基本上表明您的JS正在将图像编码为看似Base64的图像,这意味着它以代码格式发送图像(是的....)

虽然我认为这是许多API驱动的服务处理图像的方式,但必须有更好的方法来处理它


通过Ajax上传图像

这可能是不正确的,但希望能提供一些选择

上传图像就是通过请求发送图像对象。 虽然您正在使用REST API接口,但是有很多信息可以解释如何通过JQuery / Ajax发送图像对象:

我们开发了一个应用程序,然后通过标准的HTML表单(启用:multipart => :true )将图像通过Ajax发送到服务器。 您可以在http://video-conference-demo.herokuapp.com上查看(注册并上传个人资料图片)


你的错误

我会尝试使用标准的html表单, 文件字段JQuery文件上传来将文件上传到您的服务器

更改控制器中的代码

@match = Match.new(params[:match])

@match = Match.new(:pic => params[:pic])

这将破坏浏览器的兼容性,但它可以在移动客户端上运行。

为浏览器创建另一个控制器。

暂无
暂无

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

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