我还在学习很多关于Rails和Android开发的知识,如果我的问题有点不清楚,请原谅我。
从根本上说,我想做的是使用Android应用程序将照片上传到我的rails应用程序。
我有一个Rails应用程序,它使用Carrierwave和Amazon S3进行图像上传。我正在编写一个配套的Android应用程序应用程序,可用于更新网站上的条目和上传照片。我为rails应用程序创建了一个REST API,以便我可以使用Android应用程序执行http post / get /和删除请求,该应用程序用于更新文本条目。但是我不确定如何进行图像上传,因为当我查看Rails日志中的POST参数时,它包含了许多CarrierWave特定的操作(例如@headers,@ content_type,file等)。
有人可以为我推荐一种方法吗?
非常感谢!
答案 0 :(得分:0)
我最终拼凑了代码片段并获得了有效的东西。我不得不在多部分实体中发送图像:
public class uploadImage extends AsyncTask<Object, Void, HttpEntity>{
@Override
protected HttpEntity doInBackground(Object... params){
DefaultHttpClient client = new DefaultHttpClient();
String url= IMAGE_URL+"?auth_token=" + auth_token;
Log.d(TAG, "image_url: " + url);
HttpPost post = new HttpPost(url);
MultipartEntity imageMPentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try{
imageMPentity.addPart("project_id", new StringBody(projectID));
imageMPentity.addPart("step_id", new StringBody(stepID));
imageMPentity.addPart("content_type", new StringBody("image/jpeg"));
imageMPentity.addPart("filename", new StringBody(filename));
imageMPentity.addPart("imagePath", new FileBody(new File(filepath)));
post.setEntity(imageMPentity);
} catch(Exception e){
Log.e(StepActivity.class.getName(), e.getLocalizedMessage(), e);
}
HttpResponse response = null;
try {
response = client.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity result = response.getEntity();
return result;
}
protected void onPostExecute(HttpEntity result){
if(result !=null){
// add whatever you want it to do next here
}
}
}
asynctask需要文件路径和文件名。在我的应用中,我允许用户从图库中选择图像。然后我检索文件路径和文件名,如下所示:
@Override
// user selects image from gallery
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data){
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Log.d(TAG, "picturePath: " + picturePath);
filepath = picturePath;
filename = Uri.parse(cursor.getString(columnIndex)).getLastPathSegment().toString();
Log.d(TAG, "filename: " + filename);
cursor.close();
// add the image to the view
addedImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
希望有所帮助!