我正在尝试将以下数据发布到我的rails应用程序。它期望格式如下:
Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"oSJ2ut0T1HGJ+KcBAPPP4lwn8Hc4Xwkn8emVujXy9xQ=",
"wine"=>{"name"=>"nice wine", "vintage"=>"1923", "price"=>"412.2", "photo"=>#<ActionDispatch::Http::UploadedFile:0x007f9c86243d38 @tempfile=#<Tempfile:/var/folders/z9/r6hjby6x2cvfrlldtv7djz8c0000gn/T/RackMultipart20140825-4734-em8b0l>, @original_filename="timtams.jpeg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"wine[photo]\"; filename=\"timtams.jpeg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Create Wine"}
但是,我现在从我的Android应用程序中获取此信息:
Parameters: {
"photo"=>#<ActionDispatch::Http::UploadedFile:0x007f8b69bd2968 @tempfile=#<Tempfile:/var/folders/z9/r6hjby6x2cvfrlldtv7djz8c0000gn/T/RackMultipart20140827-3309-f5b613>, @original_filename="20140608_172146-3-1.jpg", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"photo\"; filename=\"20140608_172146-3-1.jpg\"\r\nContent-Type: application/octet-stream\r\n">,
"name"=>"test1",
"vintage"=>"1927",
"price"=>"19.27"}
有没有办法在参数前定义“wine”?
以下是我目前的代码:
/**
* Created by zhongqinng on 26/8/14.
*/
public class UploadAsync extends AsyncTask {
private String TAG = "UploadAsync";
@Override
protected Object doInBackground(Object[] params) {
postMyWine2();
return null;
}
public void postMyWine2(){
Log.i(TAG, "postMyWine2 start");
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(WineStoryHTTPClient.BASE_URL + "/wines");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File photofile = new File("/storage/sdcard0/Download/20140608_172146-3-1.jpg");
builder.addPart("photo", new FileBody(photofile));
builder.addTextBody("name", "test1");
builder.addTextBody("vintage", "1927");
builder.addTextBody("price", "19.27");
post.setEntity(builder.build());
Log.i(TAG,"postMyWine2 post.getParams() = "+post.getParams());
try {
Log.i(TAG,"postMyWine2 posting");
HttpResponse response = client.execute(post);
} catch (Exception e) {
Log.i(TAG,"postMyWine2 post Exception");
e.printStackTrace();
}
// HttpEntity entity = response.getEntity();
}
}
答案 0 :(得分:0)
通过在服务器端实施解决方法来管理解决问题: 改变了服务器端期望的格式。 但是,我仍然有兴趣了解如何从客户端格式化post params。
def create
# @wine = Wine.new(wine_params)
@wine = Wine.new( :name => params[:name], :vintage => params[:vintage], :price => params[:price] ,:photo => params[:photo])
respond_to do |format|
if @wine.save
format.html { redirect_to @wine, notice: 'Wine was successfully created.' }
format.json { render :show, status: :created, location: @wine }
else
format.html { render :new }
format.json { render json: @wine.errors, status: :unprocessable_entity }
end
end
end