【问题标题】:Sending FormData to Spring boot rest API get bad request 400将 FormData 发送到 Spring Boot Rest API 得到错误请求 400
【发布时间】:2021-10-07 20:50:09
【问题描述】:

我使用 Spring Boot 构建了我的 API。

   @RequestMapping(value = "/v1/users/profile-picture/update", method = RequestMethod.POST)
    public Object updateProfilePicture(Principal principal, @ModelAttribute UpdateProfilePictureDTO profile_picture){
        Long user_id = accessTokenHandler.getIdByPrincipal(principal);
        if(user_id == null)
            return new DefaultResponseDTO(201,ResponseStatus.INVALID_USER,"No such user.");

        if(profile_picture.getProfile_picture() == null)
            return new DefaultResponseDTO(201,ResponseStatus.MISSING_INPUTS,"Profile Picture is missing.");

        return userService.updateProfilePicture(user_id, profile_picture.getProfile_picture());
    }

我想向这个控制器发送一个图像文件。我尝试使用 react.js。首先,我构建 formData 并将图像附加到表单数据中。

let formData = new FormData()
 formData.append(
         'profile_picture',
          newFileList[0],
      )
           

React API 端点,

export async function profilePictureUpdate(formData) {
    //image must be send as formdata

    const response = await http.post(
        apiEndPoint + '/profile-picture/update',
        formData,
        {
            headers: {
                Authorization: `Bearer ${getJwt()}`,
                "Content-type": "multipart/form-data",
            }
        });
    console.log("response of profile picuter", response);
    return response


}

但是当提交一个图像文件时,得到一个 400 bad request。我该如何解决这个问题?

【问题讨论】:

    标签: reactjs spring-boot multipartform-data


    【解决方案1】:

    Spring Boot (2.4.x):将@ModelAttribute UpdateProfilePictureDTO profile_picture 替换为@RequestParam(value = "profile_picture") MultipartFile file,然后处理file。确保启用MultipartAutoConfiguration (docs)。如果您通过 ServletRegistrationBean 注册了一个 servlet,则向其中添加多部分配置:

    servletRegistrationBean.setMultipartConfig(new MultipartConfigElement("/tmp",
            multipartProperties.getMaxFileSize(),
            multipartProperties.getMaxRequestSize(),
            multipartProperties.getFileSizeThreshold()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多