2

I want to take file-uploads from React and sending it to springboot. I am trying to post from React FormData that will contain the key-value pair of the name of the file and a file which will be XML. So when I try to post the FormData to my backend which is Springboot, it returns:

.w.s.m.s.DefaultHandlerExceptionResolver : Resolved 
[org.springframework.web.HttpMediaTypeNotSupportedException: 
Content type 'application/json;charset=UTF-8' not supported]

and here is my React Code:

handleSubmit = (e) => {
e.preventDefault();
console.log(this.state.file[0].name);
const formData = new FormData();
var i = this.state.file.length;
console.log(i);
for (var j = 0; j < i; j++) {
    formData.append(this.state.file[j].name, this.state.file[j])
}
for (var pair of formData.entries()) {
    console.log(pair[0] + ',' + pair[1]);
}

Axios.post('http://localhost:8080/upload', {
    file:formData
  })
  .then(response=>{
      console.log(response)
  })
  ;

And here is my Springboot Controller:

@CrossOrigin
@RequestMapping(value = "/upload", consumes = "multipart/form-data", method = RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile[] file) throws IOException {
    System.out.println(file.length);
    for(MultipartFile temp : file) {
        System.out.println(temp.getOriginalFilename());
        System.out.println(temp.getSize());
        File converted = new File(temp.getOriginalFilename());
        temp.transferTo(converted);
        System.out.println(converted.getTotalSpace());
    }
        return "blah";

}

I have already tried specifying multipart/form-data in the header of the Axios post request but it did not seem to work. Is the problem in my request or is it my controller? Please let me know if you have any ideas, I've been banging my head against the wall for a couple hours trying to fix this.

kt-workflow
  • 359
  • 1
  • 3
  • 14

2 Answers2

0

Try headers: {'Content-Type': undefined}, at the time of sending request. And also make sure you have enctype="multipart/form-data" at form.

Also refer it

Romil Patel
  • 12,879
  • 7
  • 47
  • 76
0

-Can you try changing your controller to as below, Instead @RequestParam.

@RequestPart("file") MultipartFile file
  • Also just Try uploading single file for now, Lets see How it goes