【问题标题】:Can't POST multipart/form-data from React to Spring无法将多部分/表单数据从 React 发布到 Spring
【发布时间】:2019-07-11 22:14:45
【问题描述】:

我想从 React 获取文件上传并将其发送到 springboot。 我正在尝试从 React FormData 发布,它将包含文件名称的键值对和一个 XML 文件。因此,当我尝试将 FormData 发布到我的 Springboot 后端时,它会返回:

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

这是我的 React 代码:

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)
  })
  ;

这是我的 Springboot 控制器:

@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";

}

我已经尝试在 Axios 发布请求的标头中指定 multipart/form-data,但它似乎不起作用。 是我的请求中的问题还是我的控制器? 如果您有任何想法,请告诉我,我一直在努力解决这个问题几个小时。

【问题讨论】:

    标签: reactjs rest spring-boot


    【解决方案1】:

    在发送请求时尝试headers: {'Content-Type': undefined},。并确保您在表格中有enctype="multipart/form-data"

    Also refer it

    【讨论】:

    • 这两件事我都做过。还有其他建议吗?
    【解决方案2】:

    -您可以尝试将您的控制器更改为如下,而不是@RequestParam。

    @RequestPart("file") MultipartFile file
    
    • 现在也只是尝试上传单个文件,让我们看看效果如何

    【讨论】:

      猜你喜欢
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 1970-01-01
      • 2016-11-08
      • 2017-09-20
      • 2020-10-12
      • 2019-07-10
      相关资源
      最近更新 更多