REST multipart mixed request (file+json) with Spring

spring mvc multipart request with json
spring rest multipart file upload example
spring post multipart/form-data
java rest client multipart file upload
spring requestbody and multipartfile
rest api multipart/form-data java
spring boot multipart file upload example postman
how multipart request works

I need to send a file alongside with a json to my Spring Controller. I have the following controller class:

@Controller
@RequestMapping("/perform")
public class PerformController {

    ...

    @RequestMapping(path = "gopdf", method = RequestMethod.POST, consumes = { "multipart/mixed" })
    @ResponseStatus(HttpStatus.CREATED)
    public void handleFileUpload(@RequestPart("file") MultipartFile file, @RequestPart("map") String map,   HttpServletResponse response) throws Exception {
        ...
    }

}

But when I curl on my server with the following command :

 curl -H "Content-Type: multipart/form-data" -F "map=@map.json; type=application/json" -F "content=@SMP.docx" -X POST localhost:9000/perform/gopdf-i -v

I get 415 unsupported Media Type !

Any clue ?

The consumes thing in the other answers didn't do crap for me. The key was getting the specific multipart/* types I wanted to support onto some headers key in the RequestMapping. It was really difficult to figure out, mostly guess work and stare at the Spring source code. I'm kind-of underwhelmed with Spring's support for this, but I have managed to make it work in our Spring Boot App, but only with Tomcat?!? Something called the MultipartResolver chokes when you configure your Boot application to use Jetty...so long Jetty. But I digress...

In my Controller I set up for multipart/mixed or multipart/form-data like...

@RequestMapping(value = "/user/{userId}/scouting_activities", method = RequestMethod.POST,
        headers = {"content-type=multipart/mixed","content-type=multipart/form-data"})
public ResponseEntity<String> POST_v1_scouting_activities(
        @RequestHeader HttpHeaders headers,
        @PathVariable String userId,
        @RequestPart(value = "image", required = false) MultipartFile image,
        @RequestPart(value = "scouting_activity", required = true) String scouting_activity_json) {
  LOG.info("POST_v1_scouting_activities: headers.getContentType(): {}", headers.getContentType());
  LOG.info("POST_v1_scouting_activities: userId: {}", userId);
  LOG.info("POST_v1_scouting_activities: image.originalFilename: {}, image: {}",
          (image!=null) ? image.getOriginalFilename() : null, image);
  LOG.info("POST_v1_scouting_activities: scouting_activity_json.getType().getName(): {}, scouting_activity: {}",
          scouting_activity_json.getClass().getName(), scouting_activity_json);
  return new ResponseEntity<String>("POST_v1_scouting_activities\n", HttpStatus.OK);
}

That headers thing let it uniquely identify the multipart content types it was willing to take a shot at. This lets curls like...

curl -i -X POST 'http://localhost:8080/robert/v1/140218/scouting_activities' \
-H 'Content-type:multipart/mixed' \
-F 'image=@Smile_128x128.png;type=image/png' \
-F 'scouting_activity={
  "field": 14006513,
  "longitude": -93.2038253,
  "latitude": 38.5203231,
  "note": "This is the center of Dino Head.",
  "scouting_date": "2017-01-19T22:56:04.836Z"
};type=application/json'

...or...

curl -i -X POST 'http://localhost:8080/robert/v1/140218/scouting_activities' \
-H 'Content-type:multipart/form-data' \
-F 'image=@Smile_128x128.png;type=image/png' \
-F 'scouting_activity=@scoutingFrackingCurl.json;type=application/json'

work.

Multiple files upload with request body using spring boot and test , Technically it is also known as multipart request. I can send files using form-​data while request body as raw JSON but there is no way to to Here is sample Java/Spring code to expose a REST endpoint to accept multiple  public void uploadFile(@RequestParam("identifier") String identifier, @RequestParam("file") MultipartFile file){ } OR. Send Json data inside a MultipartFile and then parse Multipart file as mentioned below and thats it. public void uploadFile(@RequestParam("file") MultipartFile file){POJO p = new ObjectMapper().readValue(file.getBytes(), POJO.class); }

I've found the solution: I need to use @RequestParam instead of @RequestPart

@RequestMapping(path = "gopdf", method = RequestMethod.POST, consumes = { "multipart/form-data" })
@ResponseStatus(HttpStatus.OK)
public void handleFileUpload2(@RequestParam("file") MultipartFile file, @RequestParam("map") String jsonMap,
        HttpServletResponse response) throws Exceptio

Spring REST, Learn to upload multipart binary file (e.g. jpeg image) with Spring REST API accepting MultipartFile request and to download file using FileSystemResource. Multipart REST Service (“multipart/mixed” mime): Spring Multipart file upload service capable of consuming different kind of files like pdf, txt, json, zip etc. In Multipart project we will have HomeController resource capable of accepting the different kind of files format.

spring rest multipart, I described a multipart request in the yml where I want to combine more data (file spring rest multipart - combine file and json object #327 requestBody: description: add document required: true content: multipart/form-data:  When we Create a blob with in the stringified JSON data and append it to the FormData object. This could may cause the Content-type of the second part in the multipart request to be "application/json" instead with the file type. Send the request to the server. Request Details: Javascript Code:

It's maybe related to your request mapping annotation. I think accept value is missing to determine what service can accept :

Example :

@RequestMapping(path = "gopdf", method = RequestMethod.POST, consumes = { "multipart/mixed" }, accept = MediaType.MULTIPART_FORM_DATA_VALUE)

Import :

import org.springframework.http.MediaType;

Documentation/API : http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/MediaType.html

[solved] - Spring, [solved] - Spring - Why do the Spring MVC Multipart Request with JSON ? Rest service in Controller will have mixed @RequestPart and second part in the multipart request to be "application/json" instead with the file type. Sending multipart requests with Spring RestTemplate I had to post some image files along with some JSON data to another PHP API using Spring Rest Template. It ate my 2 days of work as it introduced issues one after other when I was fixing one by one.

Uploading MultipartFile with Spring RestTemplate, Learn how to upload files using Spring's RestTemplate. Simply put, a basic HTTP POST request body holds form data in name/value Multipart file requests break a large file into smaller chunks and use Java “Back to Basics” Tutorial · Jackson JSON Tutorial · HttpClient 4 Tutorial · REST with Spring  Above method can respond to the previously demonstrated multipart request containing a single file. This works because Spring has a built-in HTTP message converter that recognizes file parts. In addition to the javax.servlet.http.Part type, you can also convert file uploads to org.springframework.web.multipart.MultipartFile.

Multipart file upload RESTFul web service (Spring MVC/ java , Spring MVC Multipart File Upload Restful web service capable of consuming Multipart REST Service (“multipart/mixed” mime): file upload client to upload different files formats like jpg, pdf, json and zip file. We perform following changes to make it capable of consuming multipart file upload request coming from client. This is how I handled the Multipart Request using Spring 4 (This is the the case when you don't know about filenames or total no. of files in Multipart Request)

FormHttpMessageConverter (Spring Framework 5.2.6.RELEASE API), Note that "multipart/mixed" is registered as a supported media type by default. shows how to do a file upload using the "multipart/form-data" content type. for reading and writing form data when the request or response Content-Type header  A way to solve this without needing to use a FileSystemResource that requires a file on disk, is to use a ByteArrayResource, that way you can send a byte array in your post (this code works with Spring 3.2.3):

Comments
  • Using Spring Boot 2.2 and curl this solution works perfectly for me.
  • This is no longer multipart/mixed, it is multipart/form-data.
  • The problem all along was the 'consumes' part of the annotation