Abhishek
Abhishek

Reputation: 33

Required request part 'image' is not present with React and Spring Boot

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.

Backend Controller Code:

@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

Upvotes: 2

Views: 1260

Answers (2)

Abhishek
Abhishek

Reputation: 33

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: fig

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

Upvotes: 1

Ilesh Patel
Ilesh Patel

Reputation: 2155

You already set files[0] when you set

handleStudentImgChange(event) {
      this.setState({ studentImg: event.target.files[0] });
  }  

then again, you are trying to access

bodyFormData.append("studentImg", studentImg[0]);

This, seems wrong, change this to

bodyFormData.append("studentImg", studentImg);

and see if it works..

Upvotes: 1

Related Questions