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.
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;
}
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)
}
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
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