使用 spring rest 和 axios 上传文件,未找到多部分边界

File Upload using spring rest and axios, no multipart boundary was found

我在使用 spring rest and react 和 axios 上传文件时遇到了一些问题, 我的后端代码是

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity uploadFile(@RequestParam MultipartFile file) {
    return ResponseEntity.ok().build();
}

我可以使用 postman 上传文件,但是使用 axios 我遇到了一些错误。

nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

这是我的代码:

let formData = new FormData();
formData.append("file", this.state.selectedFile);

axios({
  method: "post",
  url: url,
  data: {
    formData
  }
})

如果我放

headers: { "Content-Type": "multipart/form-data" }

我也有错误, 谁能告诉我我的错误是什么?

你不需要输入任何 headers 因为它会自动决定 headers 的参数,当你手动执行时你需要明确决定一些很难判断的参数,所以不要给 headers

可能是因为您正在创建一个新对象并在对象内部发送数据 试试这个 data: formData

let formData = new FormData();
formData.append("file", this.state.selectedFile);

axios({
  method: "post",
  url: url,
  data: {  formData},
{...axios.default.headers,
...{headers: { "Content-Type": "multipart/form-data" }}

}

})