我最终拼凑了代码片段并得到了一些有用的东西。我必须在多部分实体中发送图像:
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));
}
}
希望有帮助!