Retrofit 2 file down/upload

前端 未结 5 1750
栀梦
栀梦 2020-12-13 00:54

I\'m trying to down/upload a file with retrofit 2 but can\'t find any tutorials examples on how to do so. My code for downloading is:

@GET(\"documents/checko         


        
5条回答
  •  庸人自扰
    2020-12-13 01:04

    I am using retrofit 2.0.0-beta2 and I had an issue uploading image by using multipart request. I solved it by using this answer: https://stackoverflow.com/a/32796626/2915075

    The key for me was to use standard POST with MultipartRequestBody instead of @Multipart annotated request.

    Here is my code:

    Retrofit service class

    @POST("photo")
    Call uploadPhoto(@Body RequestBody imageFile, @Query("sessionId"));
    

    Usage from activity, fragment:

    RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), imageFile);
    MultipartBuilder multipartBuilder = new MultipartBuilder();
    multipartBuilder.addFormDataPart("photo", imageFile.getName(), fileBody);
    RequestBody fileRequestBody = multipartBuilder.build();
    
    //call
    mRestClient.getRetrofitService().uploadProfilePhoto(fileRequestBody, sessionId);
    

提交回复
热议问题