如何使用Retrofit 2发送图像阵列以及每个图像的数据?

时间:2018-09-27 11:19:27

标签: android ruby-on-rails-5 retrofit2 carrierwave

假设我有这个模型

data class PhotoRequest(
  @SerializedName("page_number")
  val pageNumber: Int,
  @SerializedName("image")
  val requestBody: MultipartBody.Part
)

多部分是使用以下方法创建的:

val photo = File(picturePath)
val requestFile = RequestBody.create(
        MediaType.parse("image/jpeg"),
        photo
    )
return MultipartBody.Part.createFormData("images", photo.name, requestFile)

改造构建器是:

 val builder = Retrofit.Builder()
            .baseUrl(BuildConfig.BASE_URL)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))

这是改造界面:

@Multipart
    @POST("my_endpoint")
    fun sendExample(
        @Part("name") name: String,
        @Part("email") email: String,
        @Part("images[]") images: List<PhotoRequest>
    ): Single<String>

我要完成的工作是发送多个图像以及每个图像的一个参数,在这种情况下,是页数。

服务器(导轨)在任何请求中均无法识别图像,实际上,键“图像”内部的内容是作为字符串数组接收的。

 "images"=>["{\"page_number\":1,\"image\":{\"headers\":{\"namesAndValues\":[\"Content-Disposition\",\"form-data; name=\\\"image\\\"; filename=\\\"1537970501549.jpg\\\"\"]]}}}"]

有人知道如何正确提交此请求吗?或如何在导轨侧手动处理图像?

2 个答案:

答案 0 :(得分:0)

这就是您在api接口中声明的方式。图像列表不需要零件名称。

@Multipart
@POST("my_endpoint")
fun sendExample(
    @Part("name") name: String,
    @Part("email") email: String,
    @Part images: List<MultipartBody.Part>
): Single<String>

然后,无论您尝试发送请求的何处,都请添加此方法并创建multipartBody.part的列表

 fun prepareFilePart(partName: String, file: File): MultipartBody.Part {
    val requestFile = RequestBody.create(MediaType.parse("image/png"), file)
    return MultipartBody.Part.createFormData(partName, file.name, requestFile)
}

 val listOfImages = ArrayList<MultipartBody.Part>()
 for (i in 0 until images.size) {
     listOfImages.add(prepareFilePart("image[$i]", images[i]))
 }

然后您可以像这样发送请求:

sendExample("some name", "email@ru.org", listOfImages)

答案 1 :(得分:0)

打开多张图片的图库意图

public void choosePhotoFromGallary() {
  Intent galleryIntent = new Intent(Intent.ACTION_PICK,
    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  galleryIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
  startActivityForResult(galleryIntent, GALLERY);
}

收到多张图片的画廊意图的结果

public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == GALLERY && resultCode == RESULT_OK && data != null) {
    Uri uri = null;
    //**if Data have multiple images **
    if (data.getClipData() != null) {
      for (int index = 0; index < data.getClipData().getItemCount(); index++) {
        // Getting the URIs of the selected files and logging them into logcat at debug level
        uri = data.getClipData().getItemAt(index).getUri();
        Log.e("mutlifilesUri [" + uri + "] : ", String.valueOf(uri));
        file = new File(new FileUtils(getContext()).getPath(fileUri));
        arrayList.add(fileUri);
      }
    } else {
      uri = data.getData();
      file = new File(new FileUtils(getContext()).getPath(fileUri));
      arrayList.add(fileUri); //add the Uri in a array list
    }
  }
}

将多张图片转换成multipartBody发送到服务端

public List < MultipartBody.Part > getMultiAttachment() {
  if (arrayList != null) {
    // create part for file (photo, video, ...)
    for (int i = 0; i < arrayList.size(); i++) {
      parts.add(prepareFilePart("multifileAttachment[" + i + "]", arrayList.get(i)));
    }
  }
  return parts;
}

@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
  // use the FileUtils to get the actual file by uri

  File file = new File(new FileUtils(getContext()).getPath(fileUri));
  // create RequestBody instance from file
  RequestBody requestFile = RequestBody.create(MediaType.parse("*/*"), file);
  // MultipartBody.Part is used to send also the actual file name
  return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}

@Multipart
@POST("api_end_point")
Call < ApiResponse > hitEmailApi(@Part List < MultipartBody.Part > getMultiAttachment());