【问题标题】:Send file using retrofit that follows specific request body使用遵循特定请求正文的改造发送文件
【发布时间】:2020-04-16 22:12:33
【问题描述】:

是否可以发送如下邮递员截图所示的文件?我知道我们可以像发送顶级对象一样发送文件。如下所示:

@Multipart
@POST("audition/register-member")
Observable<ResponseObject<String>> sendAuditionData(@Part("name") RequestBody name,
                                                   @Part("contact") RequestBody contact,
                                                   @NotNull @Part("district") RequestBody district,
                                                   @Part("estdDate") RequestBody estdDate,
                                                   @Part("reason") RequestBody reason,
                                                   @Part("type") RequestBody type,
                                                   @Part("link") RequestBody link,
                                                   @Part MultipartBody.Part video,
                                                   @Part MultipartBody.Part image
                                                  );
// eg: of creating body
val name = RequestBody.create("multipart/form-data".toMediaType(), fullName)
val imageBody = MultipartBody.Part.createFormData("image", selectedFile?.getName(), fileBody); // fileBody is (ProgressRequestBody impl RequestBody)

但是我们如何发送带有文件的成员数组对象,如下面的邮递员所示。

【问题讨论】:

    标签: android postman retrofit2


    【解决方案1】:

    首先请像这样为这个 Json 创建一个数据类...

    data class ReqAuditionData(
    
    @field:SerializedName("members")
    val members: ArrayList<Members>? = ArrayList(),
    
    @field:SerializedName("name")
    val name: String = "",
    
     @field:SerializedName("district")
    val district: String = "",
    
    //same for other fields
    )
    

    然后直接把这个数据类作为参数传给接口方法...

    @Multipart
    @POST("audition/register-member")
    Observable<ResponseObject<String>> sendAuditionData(@Body reqAuditionData : ReqAuditionData);
    

    【讨论】:

    • 但是如何将文件附加到该数据类。如果我们将字段声明为文件类型,它会起作用吗?另外,multipart 是否接受 @Body 注释?如果所有字段都是文本,我以前曾使用过它。不知道这样行不行??我需要试一试。无论如何谢谢。github.com/square/retrofit/issues/1785#issuecomment-275987226
    【解决方案2】:

    这就是我使用 post 方法实现向服务器发送图像的方式

    api 文件:

    @POST("api/profilepic/")
    @Multipart
    Call<PostResult> updateProfile(@Header("Authorization") String token,
                                           @Part MultipartBody.Part file,
                                           @Part("value") RequestBody name);
    

    调用API:

    File file = new File(files[0]);
    RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
    MultipartBody.Part fileUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
    RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
    retrofit = new Retrofit.Builder()
                            .baseUrl(SERVER_NAME)
                            .client(UnsafeOkHttpClient.getUnsafeOkHttpClient())
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                    api = retrofit.create(GetRemindersApi.class);
                    Call<PostResult> call1 = api.updateProfile("Token " + token, fileUpload, filename);
                    call1.enqueue(new Callback<PostResult>() {
                        @Override
                        public void onResponse(@NonNull Call<PostResult> call, @NonNull Response<PostResult> response) {
                            PostResult result = response.body();
                            if (Objects.requireNonNull(result).getResult().equals("success")) {
                                profileImage.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
                            } else {
                                Toast.makeText(ProfileView.this, result.getError(), Toast.LENGTH_SHORT).show();
                            }
                        }
    
                        @Override
                        public void onFailure(@NonNull Call<PostResult> call, @NonNull Throwable t) {
                            Toast.makeText(ProfileView.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                });
            });
    

    它对我来说很好用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 2017-10-31
      • 2022-01-25
      • 2017-07-18
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多