MultipartFile + String as Request Param using RestTemplate in Spring

multipartfile spring boot
multipartfile flutter
spring requestbody and multipartfile
multipartfile content-type
multipartfile implementation class
modelattribute multipartfile
mockmultipartfile
multipart file upload java example

In my spring boot Application, I need to pass String value along with MultipartFile as Requestparam. Controller is below where I'm converting MultipartFile to java.io.File and then passing it to DAO controller with help of restTemplate.

Request from Angular will hit Upload Controller first then UploadController is client(Java) and it will be calling server svs-ba-dao Controller with Base URL. csvUpload contains base URL: http://localhost:8082/svs-ba-dao/csvUpload?parentPkId=&file=multipartFile

@CrossOrigin
@RestController
public class UploadController {

    private static final Logger log = LogManager.getLogger(UploadController.class);

    @Value("${salama.dao.csvUpload.rest.url}")
    private String csvUpload;

    @Autowired
    UploadHelperService uploadHelperService;

    @PostMapping(value = "/csvUpload")
    public String csvUpload(@QueryParam("parentPkId") String parentPkId, @RequestParam("file") MultipartFile file ) throws IllegalStateException, IOException{

        log.info("Calling csvUpload :" + csvUpload);
        final HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

        File cnvFile = uploadHelperService.multipartToFile(file,file.getOriginalFilename());
        System.out.println("Converted File Name is -->"+cnvFile.getName());
        final MultiValueMap<String, Object> data = new LinkedMultiValueMap<>();

        data.add("parentPkId", parentPkId);
        data.add("file", new FileSystemResource(cnvFile));

    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(data, requestHeaders);

        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> obj =restTemplate.exchange(csvUpload, HttpMethod.POST,
            requestEntity, String.class);

        return obj.getBody();
}


}

In svs-ba-dao Controller catching it as below

@RequestMapping(value="/csvUpload", method=RequestMethod.POST)
    public String csvUpload(@RequestParam String parentPkId, @RequestParam MultipartFile file) throws IOException {
        log.info("Entered method csvUpload() of svs-ba-dao.class");
        return uploadService.csvUpload(parentPkId,file);
    }

I have included these properties into the application.properties file of my application: spring.servlet.multipart.maxFileSize=1MB spring.servlet.multipart.maxRequestSize=1MB

So I start my application and call the /csvUpload that generate the POST request. i'm getting below error.

Converted File Name is -->testInput_TxnMpMotSlv.csv
2019-01-24T15:12:41,217 ERROR [[localhost].[/svs-ba-dao].[dispatcherServlet]] [http-nio-8085-exec-2] Servlet.service() for servlet [dispatcherServlet] in context with path [/svs-ba-dao] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpServerErrorException: 500 null] with root cause
org.springframework.web.client.HttpServerErrorException: 500 null
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:97) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:766) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:724) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:680) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:600) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at com.svs-ba-dao.controller.UploadController.csvUpload(UploadController.java:59) ~[classes/:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_192]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_192]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_192]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_192]

Error is in resttemplate as it is taking null, but syntactically way of calling RestTemplate is correct as i'm not getting any error. am I calling Base URLproperly?by passing requestparam values. i.e parentPkId=?&file=multipartFile

http://localhost:8082/svs-ba-dao/csvUpload?parentPkId=&file=multipartFile honestly i haven't worked on this before. Where i'm doing wrong, any leads or corrections welcomed. Thanks in advance

Here I found where I was wrong

csvUpload will hold the URL which should be passed in rest template

 @Value("${salama.dao.csvUpload.rest.url}")
        private String csvUpload;

I found that base URL: i.e csvUpload http://localhost:8082/svs-ba-dao/csvUpload?parentPkId=&file=multipartFile sending from UploadController was wrong.

No need to specify anything like multipartFile for mediaType in URL. it will automatically pick up. but for some of the URL's need to specify ?mediaType=json if sending JSON object.

Here is my updated base URL :http://localhost:8082/svs-ba-dao/csvUpload?parentPkId=&file=

Getting Started, public interface MultipartFile. A representation of an uploaded file received in a multipart request. The file contents are either stored in memory or temporarily on​  MultipartFile has a getBytes() method that returns a byte array of the file's contents. We can use this method to write the bytes to a file:

There is no problem in calling. Look at your stack trace error carefully. In csvUpload method you print this:

System.out.println("Converted File Name is -->"+cnvFile.getName());

this line printed in log:

Converted File Name is -->testInput_TxnMpMotSlv.csv

So calling was ok. problem in here:

at com.svs-ba-dao.controller.UploadController.csvUpload(UploadController.java:59)

Just check at line number 59 in csvUpload method of UploadController. you will find your error.

Look at this. how to call multipart using rest template.

MultipartFile, This quick tutorial focuses on how to upload a multipart file using Spring's RestTemplate. We'll see both a single file and multiple files – upload  The following are top voted examples for showing how to use org.springframework.web.multipart.MultipartFile.These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.

You can do a few things to understand what is actually happening:

  1. Try calling your endpoint for csvUpload in svs-ba-dao Controller from postman to see if it is working independently. Also, update your csvUpload method to

    @RequestMapping(value="/csvUpload", method=RequestMethod.POST) public String csvUpload(@RequestParam("parentPkId") String parentPkId, @RequestParam("file") MultipartFile file) throws IOException { log.info("Entered method csvUpload() of svs-ba-dao.class"); return uploadService.csvUpload(parentPkId,file); }

  2. Surround your RestTemplate call to try-catch

    ResponseEntity<String> obj =restTemplate.exchange(csvUpload, HttpMethod.POST, requestEntity, String.class);

in order to see an exception which is coming from svs-ba-dao Controller.

Uploading MultipartFile with Spring RestTemplate, You can get the content of a MultipartFile by using the getBytes method and you can write to the file using Files.newOutputStream() : public void  Learn how to Convert a Spring MultipartFile to a File. We'll cover various ways of converting a Spring MultipartFile to a File. 1. Overview. In this quick tutorial, we'll cover various ways of converting a Spring MultipartFile to a File. 2. MultipartFile#getBytes. MultipartFile has a getBytes() method that returns

How to convert a multipart file to File?, In this tutorial, I will show you how to upload and download files with a Spring Boot Rest APIs. We also use Spring Web MultipartFile interface to  In this tutorial, I will show you how to upload and download files with a Spring Boot Rest APIs. We also use Spring Web MultipartFile interface to handle HTTP multi-part requests. This Spring Boot App works with: – Angular Client – Vue Client / Vuetify Client – React Client / React Hooks Client Related Posts: […]

Spring Boot Multipart File upload example, public File convert(MultipartFile file) { File convFile = new File(file.​getOriginalFilename()); convFile.createNewFile(); FileOutputStream fos = new  The multipartFile object includes the bytes of the uploaded file that we want to store somewhere in the filesystem. My purpose is to store this bytes to a preferred location. The only reason I keep the FileUtils.touch method is to make clear that this is a new file.

org.springframework.web.multipart.MultipartFile java code examples , MultipartFile. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to  Configure CommonsMultipartResolver It is Servlet-based MultipartResolver implementation for commons-fileupload. It provides “ maxUploadSize “, “ maxInMemorySize ” and “ defaultEncoding ” settings as bean properties. The purpose of this class is to save the temporary files to the servlet container’s temporary directory.

Comments
  • surround your RestTemplate call with try catch and sysout the obj.getBody() , see what exeption raised !
  • ResponseEntity<String> obj =restTemplate.exchange(csvUpload, HttpMethod.POST, requestEntity, String.class); this is the line i'm getting error. but couldn't dig in what is root cause as syntactically its correct @sajib
  • I tried calling svs-ba-dao Controller which works fine independently. but problem is when i tried to call it from ** UploadController**.
  • can you check by adding headers = "content-type=multipart/form-data" in svs-ba-dao Controller?