Spring rest with Spring Boot: Upload MultipartFile and Json object as parameters
Yes it is possible to call your service using Postman.
Instead of sending JSON as text, create a file (e.g. test.json) containing JSON data that you want to send:
{
"teste": "abc"
}
Then in form-data section change the type of your foo
field from Text to File and choose JSON file that you've created.
And that's it. Click Send and your request should be processed without any error.
Note: Header should be left empty i.e. it should not contain any custom Content-Type value.
Posting a File and Associated Data to a RESTful WebService preferably as JSON
I asked a similar question here:
How do I upload a file with metadata using a REST web service?
You basically have three choices:
- Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
- Send the file first in a
multipart/form-data
POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata. - Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.
sending file and json in POST multipart/form-data request with axios
To set a content-type you need to pass a file-like object. You can create one using a Blob
.
const obj = {
hello: "world"
};
const json = JSON.stringify(obj);
const blob = new Blob([json], {
type: 'application/json'
});
const data = new FormData();
data.append("document", blob);
axios({
method: 'post',
url: '/sample',
data: data,
})
Spring MVC Multipart Request with JSON
This is how I implemented Spring MVC Multipart Request with JSON Data.
Multipart Request with JSON Data (also called Mixed Multipart):Based on RESTful service in Spring 4.0.2 Release, HTTP request with the first part as XML or JSON formatted data and the second part as a file can be achieved with @RequestPart. Below is the sample implementation.
Java Snippet:Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.
@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
@RequestPart("properties") @Valid ConnectionProperties properties,
@RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);
}
Front End (JavaScript) Snippet:Create a FormData object.
Append the file to the FormData object using one of the below steps.
- If the file has been uploaded using an input element of type "file", then append it to the FormData object.
formData.append("file", document.forms[formName].file.files[0]);
- Directly append the file to the FormData object.
formData.append("file", myFile, "myfile.txt");
ORformData.append("file", myBob, "myfile.txt");
- If the file has been uploaded using an input element of type "file", then append it to the FormData object.
Create a blob with the stringified JSON data and append it to the FormData object. This causes the Content-type of the second part in the multipart request to be "application/json" instead of the file type.
Send the request to the server.
Request Details:
Content-Type: undefined
. This causes the browser to set the Content-Type to multipart/form-data and fill the boundary correctly. Manually setting Content-Type to multipart/form-data will fail to fill in the boundary parameter of the request.
formData = new FormData();
formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
"name": "root",
"password": "root"
})], {
type: "application/json"
}));
Request Details:method: "POST",
headers: {
"Content-Type": undefined
},
data: formData
Request Payload:Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB
------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt
------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json
------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--
Related Topics
How to Use Variables in One Method into Another Method
How to Split a String Between Letters and Digits (Or Between Digits and Letters)
Setonclicklistener() on a Null Object Reference Error
Java.Lang.Noclassdeffounderror: Org/Springframework/Core/Env/Configurableenvironment
Error Starting Applicationcontext in Spring Boot App
Mapstruct: Map List of Objects, When Object Is Mapped from Two Objects
How to Enable Request Scope in Async Task Executor
Java - Check If Jtextfield Is Empty or Not
Springboot Data - No Property Registration Found
Jparepository Findall() Returns Empty Result
What Happens When Base and Derived Classes Each Have Variables With the Same Name
How to Skip the First Line of a CSV in Java
Shifting Characters Within a String
Showing Morning, Afternoon, Evening, Night Message Based on Time in Java
How to Pass or Send Data from Recyclerview Adapter to Fragment