如何使用Retrofit 2上传空文件?

时间:2017-05-29 10:54:43

标签: rest file-upload retrofit

我通过使用以下代码进行改造,成功设置了将图像上传到我的REST API:

        File imageFile = ImagePicker.getFileFromResult(this, resultCode, data);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("userpic", imageFile.getName(), requestFile);

        RetrofitClient.compositeSubscription.add(RetrofitClient.getService().updateProfileUserpic("Token " + RevolutionApp.getInstance().getUserToken(), body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Profile>() {
                    @Override
                    public void onCompleted() { }

                    @Override
                    public void onError(Throwable e) { }

                    @Override
                    public void onNext(Profile profile) {
                        mProfileFragment.fetchProfileData();
                    }
                }));

现在我需要将空文件(null)发送到我的API。如何实现呢?

MultipartBody.Part.createFormData("userpic", imageFile.getName(), requestFile)

不起作用

2 个答案:

答案 0 :(得分:3)

我不知道这是正确的方法,我试着这样做。工作

MultipartBody.Part fileToUpload = null;
        if (realPath != null) {
            try {
                File file = new File(realPath);
                if (file.exists()) {
                    RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
                    fileToUpload = MultipartBody.Part.createFormData("attachment", file.getName(), requestBody);
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }else{
            RequestBody attachmentEmpty = RequestBody.create(MediaType.parse("text/plain"), "");

            fileToUpload = MultipartBody.Part.createFormData("attachment", "", attachmentEmpty);
        }

注意:文件名不应为空,代替null使用空(“”)。

答案 1 :(得分:0)

这是最终解决方案:

用于更新模型的API接口方法:

public void updateProfileData(ProfilePost profile, final OnProfileUpdatedListener listener) {

    Observable<Profile> observable;
    if (profile.getUserpicPart() != null) {
        observable = RetrofitClient.getService().updateProfileData(profile.asHashMap(), profile.getUserpicPart());
    } else {
        observable = RetrofitClient.getService().updateProfileData(profile.asHashMap());
    }

    RetrofitClient.compositeSubscription.add(observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<Profile>() {
                ...
            }));
}

改造方法签名:

@PUT("/api/v1/profile/")
@Multipart
Observable<Profile> updateProfileData(@Header("Authorization") String authorization, @PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part image);

@PUT("/api/v1/profile/")
@Multipart
Observable<Profile> updateProfileData(@Header("Authorization") String authorization, @PartMap() Map<String, RequestBody> partMap);

和模型发布:

public class ProfilePost {
    MultipartBody.Part userpicPart;

    public HashMap<String, RequestBody> asHashMap() {
        HashMap<String, RequestBody> result = new HashMap<>();
        result.put("first_name", RequestBody.create(MediaType.parse("text/plain"), this.firstName));
        result.put("last_name", RequestBody.create(MediaType.parse("text/plain"), this.lastName));
        result.put("email", RequestBody.create(MediaType.parse("text/plain"), this.email));
    }
    public void getUserpicPart() {
        if (this.userpicFile == null) {
            return null;
        }
        return MultipartBody.Part.createFormData("userpic", this.userpicFile.getName(), requestFile);
    }
}