我有一个Rails应用程序,其中有一个名为matches的控制器,其中包含create方法:
我希望能够使用这个Rails服务器,使我的安卓手机能够将图像上传到该服务器。我尝试了几个相关代码示例,但是未能实现上传功能。
请问有没有什么方法可以编写一个post方法调用来上传图像?
如果有任何资源可以帮助我,请指导我去哪里找到它。
*编辑*
这是我之前尝试的代码。
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服务器,使我的安卓手机能够将图像上传到该服务器。我尝试了几个相关代码示例,但是未能实现上传功能。
请问有没有什么方法可以编写一个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