Search code examples
jsonangularjsspringspring-restcontroller

How to upload mutiple files using Spring RestController


I have a Spring RestController bean, and i would like to add a call that recieves the following structure:

 - File file1
 - Integer integer2
 - Map<CustomClass,File> remainingFilesmapping

I tried creating a DTO Object that corresponds to this structure, but i couldn't figure out how to create the corresponding JSON message on the client side (for me it's an angular js application)


Solution

  • You can't put a file into a JSON message. Instead, you will have to use the content type multipart/form-data as explained in this question: How does HTTP file upload work?

    To make this work with AngularJS, you probably need a module: File Upload using AngularJS

    Note that many modern UIs upload the file in the background and submit the rest of the form via AJAX + JSON. That means you need two different controllers in Spring (or at least two methods) and a persistence store where you can keep either piece until the other is ready.

    To give an example, you need to save the JSON somewhere (file, database) until the file upload has finished. At that time, you must read the JSON again from where you saved it and process the file with the rest of the information.

    But if the user takes a long time to fill in the rest of the form, the file might be ready, first. So you need to be able to handle this case as well.