[JAVA] [Spring Boot] Post files and other data at the same time [Axios]

things to do

Files such as images and JSON-converted data are POSTed at the same time using ʻaxios`, and on the Spring side, mapping and validation to objects are performed. In the same way, you should be able to send any data that can be parsed on the Spring side at the same time.

Execute

Java side

The endpoints are: The trick is to use @ RequestPart. It takes an integer value, a file and a JSON object and outputs them for each.

end point


@PostMapping("/api/sample")
public void sample(
        @RequestParam("intValue") Integer intValue,
        @RequestPart("file") MultipartFile multipartFile,
        @RequestPart("jsonValue") @Valid SampleObject sampleObject,
        BindingResult bindingResult
) {
    if(bindingResult.hasErrors()) {
        //Error handling
        System.out.println(bindingResult.getAllErrors());
    }

    System.out.println(intValue);
    System.out.println(multipartFile.getOriginalFilename());
    System.out.println(sampleObject.getName());
}

The objects to receive are as follows.

object


@Getter @Setter
public class SampleObject {
    @NotBlank
    private String name;
    @NotNull
    private String description;
}

JS side

The code to POST is as follows [^ indent]. The key is to specify type:'application / json' in new Blob. See comments for what to send.

POST


postSample (file) { //Have the file passed as an argument
  const sampleObject = { //Object to be JSON
    name: 'name',
    description: null //Hook on validation by setting description to null
  }

  const formData = new FormData()
  formData.append('file', file)
  formData.append('jsonValue', new Blob([JSON.stringify(sampleObject)], {type : 'application/json'}))
  formData.append('intValue', '1') //specify 1 for intValue

  axios.post('/api/sample', formData)
}

Execution result

I sent a file called 1.png. You can see that it can be processed properly including errors.

[Field error in object 'jsonValue' on field 'description': rejected value [null]; codes [NotNull.jsonValue.description,NotNull.description,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [jsonValue.description,description]; arguments []; default message [description]]; default message [must not be null]]
1
1.png
name

Code that fails

If you don't specify type:'application / json, you will get angry with ʻorg.springframework.web.HttpMediaTypeNotSupportedException: Content type' application / octet-stream' not supported request part. ʻApplication / octet-stream means that the transmission method is not specified, and if you specify JSON here, it will work properly.

[^ indent]: 2 space indent semicolonless style.

Recommended Posts

[Spring Boot] Post files and other data at the same time [Axios]
[Spring Boot] POST file array / list and other data at the same time [Axios]
Form and process file and String data at the same time with Spring Boot + Java
Spring Boot for the first time
Implementation method of linking multiple images to one post and posting at the same time
Draw a bar graph and a line graph at the same time with MPAndroidChart
Behavior noticed when adding RadioButton and initial check at the same time in code
Check the behavior of getOne, findById, and query methods in Spring Boot + Spring Data JPA
Until the use of Spring Data and JPA Part 2
Until the use of Spring Data and JPA Part 1
[Java] Method call error when inheritance and interface implementation are performed at the same time
How to use the same Mapper class in multiple data sources with Spring Boot + MyBatis
How to change application.properties settings at boot time in Spring boot
Handle Java 8 date and time API with Thymeleaf with Spring Boot
[Spring Boot] Move validation (@Validated / @Valid) at any time [Bean Validation]
[Spring Data JPA] Custom ID is assigned in a unique sequence at the time of registration.
Launch webpack-dev-server and docker-compose at the same time on Windows Terminal and display them in another pane
About the same and equivalent
Check the actual date and time at parse with Java's SimpleDateFormat
Uploading and downloading files using Ajax in Spring Boot (without JQuery)
Setting to start multiple units at the same time with Vagrant
See the behavior of entity update with Spring Boot + Spring Data JPA
Lock_version may be used for tables that tend to access and edit the same record at the same time