Search code examples
javaspringspring-mvcmultipart

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();
  }
}

Solution

  • 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?