![](/img/trans.png)
[英]Trouble Uploading Image from Android to Rails Server Using PaperClip
[英]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.