我的Springboot后端剩余API期望具有2个参数的POST请求,如下所示:-
@PostMapping(path = "/profile" , consumes = {"multipart/form-data"})
public ResponseEntity<?> addOrUpdateProfile(@RequestPart("profile") Profile profile, @RequestParam("file") MultipartFile file) {
System.out.println("file name:"+file.getOriginalFilename()+" file is here. Save it");
profileService.saveOrUpdateExpense(profile);
return new ResponseEntity<>("Expense added succcessfully", HttpStatus.OK);
}
我可以通过curl测试后端代码:-
curl -X POST -H 'Content-Type: multipart/form-data' -F profile='{ "displayName": "ma ma", "birthDate": "1999-01-01", "gender": "male"};type=application/json' -F file=@'/home/dev/Downloads/file.pdf;type=application/octet-stream' http://localhost:8080/profile
现在,我正在尝试通过axios在我的响应前端中发出相同的POST请求。我是ReactJs的新手,我不知道该怎么做。请让我知道该怎么做?
答案 0 :(得分:0)
像这样,您可以使用带有多个参数的axios帖子 并将Content-Type标头设置为文件的multipart / form-data
var formData = new FormData();
formData.append("file", '/home/dev/Downloads/file.pdf');
formData.append("data", {"displayName": "ma ma", "birthDate": "1999-01-01", "gender": "male"});
axios.post('http://localhost:8080/profile', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})