3

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();
  }
}
Kunal Utage
  • 53
  • 2
  • 6

2 Answers2

1

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();
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

If you want to use a MultipartFile, you must use the multipart/form-data mimetype when requesting. Instead of sending the JSON as request entity, you should construct a specific multipart-entity with a single field file in it.

This is how it's done: How can I make a multipart/form-data POST request using Java?

Community
  • 1
  • 1
  • The code given in the link is not working. I have already tired it. Most of it's methods are deprecated. – Kunal Utage Feb 09 '17 at 19:37
  • The code contains an updated answer for the 4.3 version of `http-client`. – Frederik Heremans Feb 09 '17 at 19:39
  • Thanks I tired http-client 4.3 It's working earlier it wasn't working – Kunal Utage Feb 09 '17 at 19:58
  • How can we send JSONObject along with the file to web service – Kunal Utage Feb 10 '17 at 06:13
  • You can include the JSON as a second multipart form field with another field name. You'll get a second `@RequestParam` in the REST controller. Just pull that file stream throug an `ObjectMapper`. Because you're using multipart miletype, you cant use the `@RequestBody` to get the JSON converted to a POJO. If the JSON data you want to combine with the file is really simple, consider flattening the data and include it as separate form-fields which contain the property values istead of a file... – Frederik Heremans Feb 10 '17 at 06:28