Axios使用对象发布多部分

4jb9z9bj  于 2022-11-23  发布在  iOS
关注(0)|答案(1)|浏览(186)

下面是我的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

6qftjkof

6qftjkof1#

为了设置内容类型,您必须传递类似文件的对象。这可以使用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,
});

相关问题