我正在尝试使用改装2.0上传图片。
我关注了此guide,并使用了 uploadFile 功能。我从链接中下载了 FileUtilis.java ,就像获取文件格式Uri的代码一样。
private void uploadFile(Uri fileUri) {
// create upload service client
FileUploadService service =
ServiceGenerator.createService(FileUploadService.class);
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", file.getName(), requestFile);
// add another part within the multipart request
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
MediaType.parse("multipart/form-data"), descriptionString);
// finally, execute the request
Call<ResponseBody> call = service.upload(description, body);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v("Upload", "success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
}
当我执行程序时,该功能转到回调onResponse ,我可以从我的服务器读取正文的响应,但我上传的图像是空白的!
功能 uploadFile 传递的 fileUri 是来自相机/图库的图片,因此我有一个按钮imageProfile,当我按下按钮时,我启动了intent像这样
imageProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, getResources().getString(R.string.select_image_str));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);
}
});
在 onActivityResult 中,我把我的Uri置于变量 uriImageProfile 之内
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return;
}
try {
uriImageProfile = data.getData();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
uploadFile方法在我的代码中被调用,并且类似但不是原始的。 我有一个类 UserControllerApi ,其中我有与我的服务器的API相关联的所有方法,所以在创建之后我调用了mehod uploadPictureProfile
UserControllerApi userControllerApi = new UserControllerApi();
userControllerApi.uploadPictureProfile(idUser, uriImageProfile, this);
由于