Home > Software design >  Axios post multipart with object
Axios post multipart with object

Time:11-19

Here is my spring boot endpoint to post file and object in one request

@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)

And it works perfect when I use postman like this: enter image description here

How can I achieve exactly the same configuration with axios. I tried many solutions and everytime I get an error like this:

 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

or this:

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

Here is my axios request

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

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

I also tried this:

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

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

I also tried setting the content-type to multipart/form-data

CodePudding user response:

In order to set content-type you have to pass file-like object. It can be done using Blob. for eg.

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,
});
  • Related