2 回答
TA贡献1790条经验 获得超9个赞
虚拟 api 接口。
public interface ApiInterface {
@Multipart
@POST(URLHelper.register)
Call<ModelProp> signUp2(@Part List<MultipartBody.Part> photos,
@PartMap Map<String, RequestBody> map;
}
现在创建要像这样发布的数据。
Map<String, RequestBody> partMap = new HashMap<>();
List<MultipartBody.Part> images = new ArrayList<>();
partMap.put("device_id", createPartFromString(deviceId)); // add data which are common for all images like device_id, device_token, device_type etc.
..
..
for (int i=0; i < upFileList.size(); i++){
images.add(prepareFilePart("provider_documents["+i+"][document]", imageFile));
partMap.add("provider_documents["+i+"][expires_at]", createPartFromString(expiry)); // add image specific data.
...
..
}
...
..
observable = apiInterface.signUp2(images, partMap).
createPartFromString方法
public RequestBody createPartFromString(String string) {
return RequestBody.create(MultipartBody.FORM, string);
}
prepareFilePart方法
private MultipartBody.Part prepareFilePart(String partName, File file){
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
return MultipartBody.Part.createFormData(partName, file.getName(),requestBody);
}
TA贡献1864条经验 获得超2个赞
像这样使用它:-
// @Multipart
@POST(URLHelper.register)
fun signUp2(@Part builder: MultipartBody ): Observable<Registration>
更新 :-
private void uploadToServer(String filePath) {
showProgressDialog();
Retrofit retrofit = RetrofitClient.getRetrofitClient(this);
ApiInterface uploadAPIs = retrofit.create(ApiInterface.class);
File file = new File(filePath);
//compressor.setDestinationDirectoryPath()
RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part part = MultipartBody.Part.createFormData("fileUpload", file.getName(), fileReqBody);
//RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "image-type");
RequestBody imgNameReqBody = RequestBody.create(MediaType.parse("multipart/form-data"), "B2B_" + System.nanoTime());
uploadAPIs.uploadImage(imgNameReqBody, part).enqueue(new Callback<UploadImageRespose>() {
@Override
public void onResponse(@NonNull Call<UploadImageRespose> call, @NonNull retrofit2.Response<UploadImageRespose> response) {
if (response.isSuccessful() && response.body() != null) {
if (response.body().getCODE().equalsIgnoreCase("SUCCESS")) {
Toast.makeText(Activity.this, "Profile Image Upload Succesfully", Toast.LENGTH_SHORT).show();
} else {
hideProgressDialog();
Toast.makeText(Activity.this, "Some Error occurred, try again", Toast.LENGTH_SHORT).show();
}
} else {
hideProgressDialog();
}
}
@Override
public void onFailure(@NonNull Call<UploadImageRespose> call, @NonNull Throwable t) {
Timber.d(TAG, t.getMessage());
hideProgressDialog();
Toast.makeText(Activity.this, "Some Error occurred, try again", Toast.LENGTH_SHORT).show();
}
});
}
在您的界面中添加以下方法:-
@Multipart
@POST("Your Path Here")
Call<UploadImageRespose> uploadImage(@Part("img_name") RequestBody img_name,
@Part MultipartBody.Part file);
添加回答
举报