8

I am trying to upload data from an app to a spring backend service. Things to upload are a DataModel containing data of the object to create and several images linked to the data. Therefore I am using this method signature:

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public Survey createSurvey(@RequestBody SurveyPostHelper helper, @RequestParam(value="file", required = true) MultipartFile[] images)

I tried to play with the annotations, but either I get a blank images array or my helper is empty. How would you solve this?

Thanks in advance.

Yannick Wiesner
  • 219
  • 1
  • 2
  • 8

2 Answers2

13

I found out, that this method signature could do the job:

@ResponseBody
public Survey createSurvey(@RequestPart(required=true) SurveyPostHelper helper, @RequestPart(value="file", required = true) final MultipartFile[] images)

Important in my case was to set the MimeType in the client app. The files MimeType should be image/jpg and the SurveyPostHelpers to application/json to allow Spring to parse the json and bind it to my Object.

Yannick Wiesner
  • 219
  • 1
  • 2
  • 8
  • 1
    could you please show your client app? are you sending it with ajax? – kavain Feb 27 '18 at 15:31
  • I am sending from an iOS application with the Alamofire lib. It uses a multipart POST request to upload multipe images and a JSON object. This should be possible via AJAX, too. – Yannick Wiesner Feb 28 '18 at 14:32
3

see an example of the client code working for me images is the list of files I want to save

var formData = new FormData();

for (var i = 0; i < images.length ; i++) {
  formData.append('images', images[i]);
}

formData.append('adData', new Blob([JSON.stringify(adData)], {
    type: "application/json"
}));