POST Multipart Form Data using Retrofit 2.0 including image

前端 未结 10 1741
名媛妹妹
名媛妹妹 2020-11-22 11:07

I am trying to do a HTTP POST to server using Retrofit 2.0

MediaType MEDIA_TYPE_TEXT = MediaType.parse(\"text/plain\");
MediaType MEDIA_TYPE         


        
10条回答
  •  無奈伤痛
    2020-11-22 11:49

    in kotlin its quite easy, using extensions methods of toMediaType, asRequestBody and toRequestBody here's an example:

    here I am posting a couple of normal fields along with a pdf file and an image file using multipart

    this is API declaration using retrofit:

        @Multipart
        @POST("api/Lesson/AddNewLesson")
        fun createLesson(
            @Part("userId") userId: RequestBody,
            @Part("LessonTitle") lessonTitle: RequestBody,
            @Part pdf: MultipartBody.Part,
            @Part imageFile: MultipartBody.Part
        ): Maybe>
    

    and here is how to actually call it:

    api.createLesson(
                userId.toRequestBody("text/plain".toMediaType()),
                lessonTitle.toRequestBody("text/plain".toMediaType()),
                startFromRegister.toString().toRequestBody("text/plain".toMediaType()),
                MultipartBody.Part.createFormData(
                    "jpeg",
                    imageFile.name,
                    imageFile.asRequestBody("image/*".toMediaType())
                ),
                MultipartBody.Part.createFormData(
                    "pdf",
                    pdfFile.name,
                    pdfFile.asRequestBody("application/pdf".toMediaType())
                )
    

提交回复
热议问题