改造将多个图像上传到单个密钥

Kar*_*eek 23 android multipartform-data okhttp retrofit2

我正在使用Retrofit将图像上传到我的服务器.在这里,我需要为单个密钥上传多个图像.我已经尝试使用Postman Web客户端,它运行良好.这是一个截图.在此输入图像描述

以下是请求的键值对.
SurveyImage:[file1,file2,file3];
PropertyImage:文件
DRA:jsonBody

我试图用Retrofit做同样的事情.但图像没有上传到服务器.这是我的代码.
WebServicesAPI.java

public interface WebServicesAPI {
    @Multipart
    @POST(WebServices.UPLOAD_SURVEY)
    Call<UploadSurveyResponseModel> uploadSurvey(@Part MultipartBody.Part surveyImage, @Part MultipartBody.Part propertyImage, @Part("DRA") RequestBody dra);
}
Run Code Online (Sandbox Code Playgroud)

这是上传文件的方法.

 private void requestUploadSurvey() {
        File propertyImageFile = new File(surveyModel.getPropertyImagePath());
        RequestBody propertyImage = RequestBody.create(MediaType.parse("image/*"), propertyImageFile);
        MultipartBody.Part propertyImagePart = MultipartBody.Part.createFormData("PropertyImage", propertyImageFile.getName(), propertyImage);
        JSONObject requestBody = getRequestBody();
        RequestBody draBody = null;
        try {
            draBody = RequestBody.create(MediaType.parse("text/plain"), requestBody.toString(1));
            Log.d(TAG, "requestUploadSurvey: RequestBody : " + requestBody.toString(1));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        MultipartBody surveyImage = null;

            for (SurveyModel.PictureModel model : surveyModel.getPicturesList()) {
                File file = new File(model.getImagePath());
                builder.addFormDataPart("SurveyImage", file.getName(),
                        RequestBody.create(MediaType.parse("image/*"), file));
            }
            surveyImage = builder.build();

        final WebServicesAPI webServicesAPI = RetrofitManager.getInstance().getRetrofit().create(WebServicesAPI.class);
        Call<UploadSurveyResponseModel> surveyResponse = null;

            surveyResponse = webServicesAPI.uploadSurvey(MultipartBody.Part.createFormData("SurveyImage", "SurveyImage", surveyImage), propertyImagePart, draBody);

        surveyResponse.enqueue(this);

        Log.d(TAG, "requestUploadSurvey: sent the request");
    }
Run Code Online (Sandbox Code Playgroud)

请帮我解决一下这个.

Kar*_*eek 34

我们可以使用MultipartBody.Part数组将图像数组上传到单个键.这是解决方案
WebServicesAPI

public interface WebServicesAPI { 
    @Multipart
    @POST(WebServices.UPLOAD_SURVEY)
    Call<UploadSurveyResponseModel> uploadSurvey(@Part MultipartBody.Part[] surveyImage, @Part MultipartBody.Part propertyImage, @Part("DRA") RequestBody dra);
}
Run Code Online (Sandbox Code Playgroud)

这是上传文件的方法.

private void requestUploadSurvey() {
  File propertyImageFile = new File(surveyModel.getPropertyImagePath());
    RequestBody propertyImage = RequestBody.create(MediaType.parse("image/*"), propertyImageFile);
    MultipartBody.Part propertyImagePart = MultipartBody.Part.createFormData("PropertyImage", propertyImageFile.getName(), propertyImage);

    MultipartBody.Part[] surveyImagesParts = new MultipartBody.Part[surveyModel.getPicturesList().size()];

    for (int index = 0; index < surveyModel.getPicturesList().size(); index++) {
        Log.d(TAG, "requestUploadSurvey: survey image " + index + "  " + surveyModel.getPicturesList().get(index).getImagePath());
        File file = new File(surveyModel.getPicturesList().get(index).getImagePath());
        RequestBody surveyBody = RequestBody.create(MediaType.parse("image/*"), file);
        surveyImagesParts[index] = MultipartBody.Part.createFormData("SurveyImage", file.getName(), surveyBody);
    }

    final WebServicesAPI webServicesAPI = RetrofitManager.getInstance().getRetrofit().create(WebServicesAPI.class);
    Call<UploadSurveyResponseModel> surveyResponse = null;
    if (surveyImagesParts != null) {
        surveyResponse = webServicesAPI.uploadSurvey(surveyImagesParts, propertyImagePart, draBody);
    }
    surveyResponse.enqueue(this);
}
Run Code Online (Sandbox Code Playgroud)

  • 我不能使用`MultipartBody.Part []`上传多个图像,它总是只上传数组中的最后一个图像.你能说清楚你在哪里使用图像阵列的键.提前致谢. (2认同)
  • 仅上传`first`图像`MultipartBody.Part [] surveyImagesParts =新MultipartBody.Part [MySharedPreferences.all_sharedprefrenceaddimage.size()]; 对(INT I = 0; I <MySharedPreferences.all_sharedprefrenceaddimage.size();我++){文件文件=新的文件(MySharedPreferences.all_sharedprefrenceaddimage.get(I)); RequestBody surveyBody = RequestBody.create(MediaType.parse("image"),file); surveyImagesParts [i] = MultipartBody.Part.createFormData("photos []",file.getName(),surveyBody); }` (2认同)
  • 在createFormData的第一个参数的字符串末尾添加[]可以解决仅上传一个图像的问题。`surveyImagesParts.add(MultipartBody.Part.createFormData(“ images []”,file.getName(),surveyBody));` (2认同)

Imr*_*med 24

我在接受的时候浪费了很多时间.但这在我的情况下不起作用.经过大量的搜索,我找到了这个.在我的情况下,它100%工作.

private void uploadMultiFile() {


    ArrayList<String> filePaths = new ArrayList<>();
    filePaths.add("storage/emulated/0/DCIM/Camera/IMG_20170802_111432.jpg");
    filePaths.add("storage/emulated/0/Pictures/WeLoveChat/587c4178e4b0060e66732576_294204376.jpg");
    filePaths.add("storage/emulated/0/Pictures/WeLoveChat/594a2ea4e4b0d6df9153028d_265511791.jpg");

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

    builder.addFormDataPart("user_name", "Robert");
    builder.addFormDataPart("email", "mobile.apps.pro.vn@gmail.com");

    // Map is used to multipart the file using okhttp3.RequestBody
    // Multiple Images
    for (int i = 0; i < filePaths.size(); i++) {
        File file = new File(filePaths.get(i));
        builder.addFormDataPart("file[]", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
    }


    MultipartBody requestBody = builder.build();
    Call<ResponseBody> call = uploadService.uploadMultiFile(requestBody);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            Toast.makeText(MainActivity.this, "Success " + response.message(), Toast.LENGTH_LONG).show();




        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

            Log.d(TAG, "Error " + t.getMessage());
        }
    });


}
Run Code Online (Sandbox Code Playgroud)

这是界面

@POST("/upload_multi_files/MultiPartUpload.php")
Call<ResponseBody> uploadMultiFile(@Body RequestBody file);
Run Code Online (Sandbox Code Playgroud)

  • @Body 参数不能与表单或多部分编码一起使用。得到这个错误。 (2认同)
  • @Ali_Waris我通过将“requestBody.parts()”传递给方法而不是requestBody对象解决了这个错误。然后在 Retrofit API 界面中,我将“@Body RequestBody 文件”更改为“@Part List&lt;MultipartBody.Part&gt; 文件”。我希望它有帮助。 (2认同)

小智 7

我尝试过的最佳解决方案

Api接口:

@Multipart
    @POST("person/img")
    Call<ResponseBody> upImageMany(@Part List<MultipartBody.Part> file);
Run Code Online (Sandbox Code Playgroud)

活动:

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

for (int i=0; i < upFileList.size(); i++){
    parts.add(prepareFilePart("my_file["+i+"]", upFileList.get(i)));
}

private MultipartBody.Part prepareFilePart(String partName, Uri fileUri){

        File file = new File(getPath(fileUri));

        RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);

        return MultipartBody.Part.createFormData(partName, file.getName(),requestBody);
    }
Run Code Online (Sandbox Code Playgroud)