【问题标题】:Axios post multipart with objectAxios 使用对象发布多部分
【发布时间】:2022-11-19 06:39:06
【问题描述】:

这是我的spring boot端点,用于在一个请求中发布fileobject

@PostMapping(
    value = ["/add"],
    consumes = [
        MediaType.MULTIPART_FORM_DATA_VALUE,
        MediaType.APPLICATION_JSON_VALUE,
        MediaType.APPLICATION_FORM_URLENCODED_VALUE,
        MediaType.APPLICATION_OCTET_STREAM_VALUE
    ]
)
fun addUser(
    @RequestPart("user") user: UserDTO,
    @RequestPart("file") file: MultipartFile,
): Long = userService.addUser(user, file)

当我像这样使用 postman 时,它工作得很好:

我怎样才能实现与axios完全相同的配置。我尝试了很多解决方案,每次出现这样的错误:

 org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded

或这个:

org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

这是我的axios请求

 const file = new FormData()
 file.append('file', photo, photo.name)

     const response = await axios.post(
        '/user/add',
        JSON.stringify({
            user,
            file
       }),
          {
            withCredentials: true,
          }
    )

我也试过这个:

 const file = new FormData()
 file.append('file', photo, photo.name)

     const response = await axios.post(
        '/user/add',
        {
            user,
            file
       },
          {
            withCredentials: true,
          }
    )

我还尝试将 content-type 设置为 multipart/form-data

【问题讨论】:

    标签: javascript spring-boot axios


    【解决方案1】:

    为了设置内容类型,您必须传递类似文件的对象。 可以使用 Blob 来完成。 例如。

    const user ={
      username: "user123"
    };
    const json = JSON.stringify(user);
    const blob = new Blob([json],{
      type: 'application/json'
    });
    
    const body = new FormData();
    body.append("user" ,blob);
    body.append("file" ,photo);
    
    axios({
      method: 'post',
      url: '/user/add',
      data: body,
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-16
      • 2018-06-20
      • 2020-07-01
      • 2017-05-11
      • 2019-06-18
      • 2023-03-26
      • 2021-01-16
      • 2017-05-20
      相关资源
      最近更新 更多