Spring Boot multipartfile always null

前端 未结 5 1828
悲&欢浪女
悲&欢浪女 2021-02-04 10:02

I am using Spring Boot version = \'1.4.0.RC1\' with Spring Boot Stormpath 1.0.2.

I am trying to use multipart file upload but the MultipartFile is always null in the con

5条回答
  •  自闭症患者
    2021-02-04 10:32

    I found out that the problem was the way I was building my request with Retrofit.

    Spring's multipart resolver requires the filename for the file to be present in content-disposition field of the part. Without this, it doesn't add the file into the multipart request.

    According to the info found here: https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server, my API interface should be:

    @Multipart
    @POST("users/{username}/profilePhoto")
    Call uploadProfilePhoto(@Path("username") String username,
                                  @Part MultipartBody.Part profilePhoto);
    

    And then when making the call in my test:

    // Given
    String usernamme = usernames[0];
    Resource testImageResource = context.getResource("classpath:images/test_image.jpg");
    File imageFile = testImageResource.getFile();
    RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
    MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", imageFile.getName(), requestFile);
    
    // When
    Response response = testApi.uploadProfilePhoto(usernamme, filePart).execute();
    

提交回复
热议问题