0

When I hit my imageupload endpoint, the imageFile is coming back null. Is there a centralized configuration I need to set somewhere to parse this? imageMetadata comes through just fine.

  @PostMapping(value = "/images/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String upload(
      @RequestPart(value = "imageFile", required = false) MultipartFile imageFile,
      @RequestPart(value = "imageMetadata", required = false) String imageMetadata
      ) {
    String imageFileIsNull = Boolean.toString(imageFile == null);
    return "Thanks for uploading your file! metadata:" + imageMetadata + " file is null: " + imageFileIsNull;
  }

Return value when I attach a photo (I've tried both jpg and png)

Thanks for uploading your file! metadata: hi file is null: true
stk1234
  • 1,036
  • 3
  • 12
  • 29

2 Answers2

1

Try with the following code snippet.

@PostMapping(value = "/images/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<ResponseMessage> upload(
      @RequestParam("file") MultipartFile imageFile
      ) {

    String imageFileIsNull = Boolean.toString(imageFile == null);
    String message = "Thanks for uploading your file! " + " file is null: " + imageFileIsNull;
    return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
  }

I removed image meta data for testing so that you can ensure that the code is working.

Sambit
  • 7,625
  • 7
  • 34
  • 65
  • That works - is there a way to send it in the body rather than in the params? – stk1234 May 23 '20 at 17:49
  • For that, you can check this. https://stackoverflow.com/questions/56349001/upload-multiple-files-with-additional-information-spring-restcontroller – Sambit May 23 '20 at 18:02
  • That sends the file in the params. I'd like to send it in 2 request parts if I can as it's a little more secure. – stk1234 May 23 '20 at 18:09
0

Figured it out. The consumes part needed to be multipart/form-data

  @PostMapping(value = "/images/upload", consumes = { "multipart/form-data" } )
  public String upload(
      @RequestPart(value = "file", required = false) MultipartFile imageFile,
      @RequestPart(value = "imageMetadata", required = false) String imageMetadata
      ) {
    String imageFileIsNull = Boolean.toString(imageFile == null);
    String imageName = imageFile.getOriginalFilename();
    return "Thanks for uploading your file! metadata:" + imageMetadata + " file is null: " + imageFileIsNull + " file name: " + imageName;
  }

output

Thanks for uploading your file! metadata:"hellooo" file is null: false file name: image_name.png
stk1234
  • 1,036
  • 3
  • 12
  • 29