改进Android Marshmallow上方的Multipart API获取错误java.lang.IllegalStateException:Multipart body必须至少有一个部分

时间:2018-03-29 06:01:08

标签: java android retrofit retrofit2

我正在使用改装2获取错误。它在Android Marshmallow以下的设备中正常工作。在Marshmallow上方给出以下误差

>java.lang.IllegalStateException: Multipart body must have at least one part.

代码

    MultipartBody.Builder builder = new MultipartBody.Builder();
    builder.setType(MultipartBody.FORM);


    try {
        for (int i = 0; i < filePaths.size(); i++) {
            File file = new File(filePaths.get(i));
            String mFileName = App.getInstance().getPrefs().getUserId() + "_" + new Date().getTime() + file.getName();
            builder.addFormDataPart("file[]", mFileName, RequestBody.create(MediaType.parse("multipart/form-data"), file));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    MultipartBody requestBody = builder.build();
    APIInterface appInterface = APIClient.getClient().create(APIInterface.class);
    Call<ResponseBody> call = appInterface.uploadMultiFile(requestBody);

    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
            try {
                if (response.isSuccessful()) {
                    view.onFileUploaded();
                } else {
                    view.showToast();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
            view.showToast();
        }
    });

请帮助我

2 个答案:

答案 0 :(得分:1)

这是我使用Request Body上传图片的方式。

RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), selectedImage /* file name*/);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("image", selectedImage.getName(), fileBody);

并在您的界面类

 @Multipart
    @POST(UPLOAD_IMAGE)
    Call<JsonObject> uploadImage(@Part MultipartBody.Part image);

它适用于所有设备..希望它可以帮助你。

答案 1 :(得分:1)

本教程将帮助您解决问题 https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server

用于多文件上传使用此

    List<MultipartBody.Part> projectParts = new ArrayList<>();

    for (int i = 0; i < mFilesTobeincluded.size(); i++) {
        File file = new File(mFilesTobeIncluded.get(i));
        String boundary = String.valueOf(System.currentTimeMillis());

        Log.d(TAG, "requestUpload: image " + i + "  " + mFilesTobeincluded.get(i));
        RequestBody requestFile =
                RequestBody.create(
                        MediaType.parse("multipart/form-data; boundary=" + boundary),
                        file
                );
        projectParts.add(MultipartBody.Part.createFormData("name_of_key", file.getName(), requestFile));
    }