in

How to upload a JSON that includes an image file to a Spring Boot Rest API


I am currently using the fetch API to post a JSON object to a REST API created with Spring Boot. I am using formData to read in the form data and store it in a JSON object:

 const data = new FormData(form);
 const formJson = Object.fromEntries(data.entries());
 let responsePromise = await fetch(
        "http://localhost:8080/api/v1/student?id=" + studentId, {
          method: 'PUT',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(formJson)
        });

The Spring Boot backend expects a JSON that corresponds to the Student entity class, which will eventually be stored in my database:

@PutMapping
    public ResponseEntity<Student> updateStudent(@RequestBody Student student, @RequestParam Long id) {
        Student currentDatabaseEntry = studentService.getStudent(id);
        currentDatabaseEntry.setFirstName(student.getFirstName());

        ...

        return new ResponseEntity<>(currentDatabaseEntry , HttpStatus.FOUND);
    }

This works fine.

Now, I have added a variable to the Student entity, which is of type byte[] and is suppossed to store an image of the student. So, I want to add an entry to my JSON object with key image and the value being a multipart file (the value of an input field of type “file”).

From what I have read on the internet, it seems that whenever I want to upload a file, I should not upload a JSON, but instead the formData object. I fail to see how to handle this request on my backend though – doesn’t Spring Boot expect the @RequestBody of the PUT request to be a JSON that resembles my Student entity?

Anyways, does anyone know how to achieve this?



Source: https://stackoverflow.com/questions/70559587/how-to-upload-a-json-that-includes-an-image-file-to-a-spring-boot-rest-api

Scanner Class with Delimiters Example in Java

A basic Vue.js dashboard template integrated with Firebase Auth and build with Vue Material