Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot Multipart file upload using Client Side Java Code

I have written a restful web service in spring boot which receives the file.

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public void uploadFile(@RequestParam("file") MultipartFile uploadfile) {
    System.out.println("filename: " + uploadfile.getName());
}

How can we upload the file from client side java code to web service. Instead of AJAX call or HTML page form multipart request?

The code below call the web service with JSON object. Like this I want to receive the file in above written web service.

void clientRequest(String server_url, JSONObject fileObj){

  try {

    URL url = new URL(server_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");

    OutputStream os = conn.getOutputStream();
    os.write(fileObj.toString().getBytes());
    os.flush();

    BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        logger.info("output :: " + output);
    }

    conn.disconnect();

  } catch (Exception e) {
    e.printStackTrace();
  }
}
like image 852
Kunal Utage Avatar asked Sep 16 '26 12:09

Kunal Utage


1 Answers

You can use Spring's HttpEntity along with ByteArrayResource to upload the file, here is an example:

MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>();
ByteArrayResource resource = new ByteArrayResource(file.getBytes()) {
    @Override
    public String getFilename() {
        return file.getName();
    }
};
data.add("file", resource);

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

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

final ResponseEntity<<SomeClass>> responseEntity = restTemplate.exchange(<url>, 
        HttpMethod.POST, requestEntity, new ParameterizedTypeReference<SomeClass>(){});

SomeClass result = responseEntity.getBody();
like image 186
Darshan Mehta Avatar answered Sep 19 '26 01:09

Darshan Mehta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!