我目前正在我的 Android 应用程序中使用 Retrofit 上传图像文件。有人可以指导我在改造请求中正确传递图像文件吗?
您需要在改造中传递多个部分对象:
MultipartBody.Part carImage = null;
if (!TextUtils.isEmpty(imagePath)) {
File file = FileUtils.getFile(getContext(), imagePath);
// create RequestBody instance from file
final RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
carImage = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
}
第1步:首先初始化服务类
public interface ImageUploadService {
@Multipart
@POST("upload")
Call<ResponseBody> upload(
@Part("description") RequestBody description,
@Part MultipartBody.Part file
);
}
第2步:在下一步中使用它来上传图像或文件
private void uploadFile(Uri fileUri) {
// create upload service client
FileUploadService service =
ServiceGenerator.createService(ImageUploadService.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(getContentResolver().getType(fileUri)),
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(
okhttp3.MultipartBody.FORM, 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());
}
});
}
第3步:你可以这样使用
uploadFile(Uri.fromFile(new File("/sdcard/cats.jpg")));
在您的活动中。
最后一步:您需要添加
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
在清单中还有
<uses-permission android:name="android.permission.INTERNET"/>
参考这个。
您可以上传任何类型的文件。
/* Create interface like below. */
public interface uploadWishImage {
@Multipart
@POST("upload/image")
Call<JsonObject> postImage(@Part MultipartBody.Part image, @Part("name") RequestBody name);
}
/* image upload code */
File file = new File("here your file path");
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "file");
uploadWishImage postService = RetrofitApi.makeNetworkRequestWithHeaders(AddWish.this).create(uploadWishImage.class);
Call<JsonObject> call = postService.postImage(body, name);
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
// somethings to do with reponse
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
// Log error here since request failed
}
});
public static MultipartBody.Part UploadImage(String filePath,String param) {
MultipartBody.Part body = null;
try {
body = MultipartBody.Part.createFormData("", "", null);
} catch (Exception e) {
e.printStackTrace();
}
//profileUpdateRequest.setWebsite(lblWebsite.getText().toString().trim());
if ((!filePath.equals(""))) {
File file = new File(filePath);
RequestBody photo = RequestBody.create(MediaType.parse("image/*"), file);
body = MultipartBody.Part.createFormData(param, file.getName(), photo);
}
return body;
步骤::1传递文件路径,它将返回您的MultiPart正文
@Multipart
@POST(Endpoint.POST_URL)
Call<DecisionStepThirdResponse> uploadUserProfile(@Part("api_id") RequestBody api_id,
@Part("api_secret") RequestBody api_secret,
@Part("api_request") RequestBody api_request,
@Part("data") RequestBody data,
@Part MultipartBody.Part profile_image);
==========================
第2步:像这样传递请求
public void uploadUserProfile(UpdateImageRequest request, MultipartBody.Part file, Callback<UpdateImageResponse> callback) {
String api_request = "uploadUserProfile";
String data = new Gson().toJson(request);
IRoidAppHelper.Log("application_form_permission", data);
json().uploadUserProfile(
RequestBody.create(MediaType.parse("text/plain"), api_id),
RequestBody.create(MediaType.parse("text/plain"), api_secret),
RequestBody.create(MediaType.parse("text/plain"), api_request),
RequestBody.create(MediaType.parse("text/plain"), data)
, file).enqueue(callback);
}
第 3 步:并在您的 Serviceclass 中传递参数