Issue
I am getting "MissingServletRequestPartException
: Required request part 'studentImg' is not present", It works fine with Postman but not with React
. I am trying to call a end point in a 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 Components' Code Snippets:
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);
React Axios Call:
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);
};
The network log: enter image description here enter image description here
I'm unable to find any solution regarding that. Please give suggestions.
Thanks in Advance :D
Solution
First I changed these lines:
let bodyFormData = new FormData();
bodyFormData.append("studentImg", studentImg[0]);
With these:
const bodyFormData = new FormData();
const blob = new Blob([studentImg], {type: studentImg.type});
bodyFormData.append("studentImg", blob);
When I logged studentImg
just above the bodyFormData
, I get the response something like: {type: 'ADD_STUDENT_IMG', studentImg: File}
where it was json object like this:
Then, I put thse lines and these are just working fine with it.
const bodyFormData = new FormData();
const blob = new Blob([studentImg.studentImg], {
type: studentImg.studentImg.type,
});
bodyFormData.append("studentImg", blob);
To understand how these lines are working:
Please read the FormData
docs and also some additional information about how it's serialized over here.
If any queries, please ask. (P.S. prescriptionImg == studentImg
for fig.)
Thanks :D
Answered By - Abhishek
Answer Checked By - Pedro (JavaFixing Volunteer)