【发布时间】: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