title: Multipart file upload with OkHttp + Spring
body: <p>I recently switched to <code>OkHttp</code>. After the switch, the code below does the upload. </p>
  
  <pre><code>RequestBody requestBody = new MultipartBuilder()
                          .type(MultipartBuilder.FORM)
                          .addPart(
                                  Headers.of("Content-Disposition", "form-data; name=\"qqfile\""),
                                  RequestBody.create(
                                          MediaType.parse(filename),
                                          new File(filename)))
                          .build();
  </code></pre>
  
  <p>If you compare images, the second image has <code>multipartFiles</code> <code>size = 0</code>. It should be of <code>size = 1</code>. How to populate <code>multipartHttpRequest</code> correctly  using <code>OkHttp</code> to make server accept successful upload?</p>
  
  <p><img src="https://i.stack.imgur.com/qC1ai.png" alt="Correct">
  <img src="https://i.stack.imgur.com/0ubrS.png" alt="In-Correct"></p>
  
  <p>Controller code </p>
  
  <pre><code>import org.apache.commons.fileupload.servlet.ServletFileUpload;
  
  import org.springframework.http.MediaType;
  import org.springframework.web.multipart.MultipartFile;
  import org.springframework.web.multipart.MultipartHttpServletRequest;
  import org.springframework.web.util.WebUtils;
  
  @RequestMapping (
          method = RequestMethod.POST,
          value = "/upload",
          produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"
  )
  public String upload(
          HttpServletRequest request,
          HttpServletResponse response
  ) throws IOException {
      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
      if (isMultipart) {
          MultipartHttpServletRequest multipartHttpRequest = 
          WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
  
          final List&lt;MultipartFile&gt; files = multipartHttpRequest.getFiles("qqfile");
  
          if (files.isEmpty()) {
              LOG.error("qqfile name missing in request or no file uploaded");
              return some error code here
          }
  
          MultipartFile multipartFile = files.iterator().next();
          //process file code below
      }
      return failure;
  }
  </code></pre>