Spring java file and data upload

Spring java file and data upload

If you need to make a service endpoint in spring that takes a file and some structured data, like json, you might find that spring is less than happy about that working in the normal way you might be used to.

In order to make this work, you want the endpoint to take a multipartFile object and a string object. Using a domain object and hoping spring marshals it will not work. Below is an example of how to do this in Spring 5.

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

  @PostMapping("/dataAndFile")
  public ResponseEntity dataAndFileUpload(
      @RequestPart(value = "dataInput") String dataInput,
      @RequestPart(value = "csv") MultipartFile csv
  ) throws IOException {

    ObjectMapper bulkObject = new ObjectMapper();
    HashMap input = bulkObject.readValue(dataInput, HashMap.class);
    InputStream thefile = csv.getInputStream();

    return new ResponseEntity(HttpStatus.OK);
  }



Powered by Adsense Deluxe Revived