【发布时间】:2022-01-17 23:53:36
【问题描述】:
我收到“MissingServletRequestPartException:所需的请求部分‘studentImg’不存在”,它适用于 Postman,但不适用于 React。我正在尝试在 Spring boot restful API 中调用端点。
后端控制器代码:
@PostMapping("/add")
public ResponseEntity<StudentFile> addStudentImg(HttpServletRequest request, @RequestParam("studentImg") MultipartFile studentImg) {
boolean isStudent = (Boolean) request.getAttribute("isStudent");
if(false == isStudent) {
throw new EtAuthException("Only Student can add their image.");
} else {
Long addedBy = (Long) request.getAttribute("studentId");
StudentFile studentFile = studentFileService.addStudentImg(studentImg, addedBy);
return new ResponseEntity<>(studentFile, HttpStatus.CREATED);
}
}
React 组件的代码片段:
handleStudentImgChange(event) {
this.setState({ studentImg: event.target.files[0] });
}
handleOnSubmit(event) {
event.preventDefault();
const { studentImg } = this.state;
this.props.addStudentImg(studentImg);
this.setState({ studentImg: null });
}
const mapDispatchToProps = (dispatch) => {
return {
addStudentImg: (studentImg) => {
dispatch(addStudentImgAction(studentImg));
},
};
export default connect(null, mapDispatchToProps)(AddStudentImgPage);
响应 Axios 调用:
import axios from "axios";
const token = "...";
export const addStudentImg = (studentImg) => {
let bodyFormData = new FormData();
bodyFormData.append("studentImg", studentImg[0]);
const headers = {
Authorization: `Bearer ${token}`,
// Accept: "application/json",
"Content-Type": "multipart/form-data",
};
return axios
.request({
method: "POST",
url: "http://localhost:8080/api/studentfiles/add/",
data: bodyFormData,
headers: headers,
})
.then((res) => res.data);
};
网络日志:enter image description hereenter image description here
我无法找到任何解决方案。请提供建议。
在此先感谢:D
【问题讨论】:
-
你能补充一下,你的网络日志对于这个请求是什么样的吗?
-
@IleshPatel 我已经添加了网络日志 {headers, payload},如果您还需要其他内容,请告诉我...还有
prescriptionImg == studentImg
标签: javascript java reactjs spring-boot axios