title: Multipart Image upload post request processed by servlet
body: <p>i have to upload an image on server using servlet and request to servlet is going through a post Method .
  Code for post the request is as follows: </p>
  
  <pre><code>public class PostImageRequest {
  public static void main(String[] args) throws Exception {
  
      final String exsistingFileName = "E:\\Users\\snikhil\\Downloads\\qwe.jpg";
      File binaryFile = new File(exsistingFileName);
      String param = "value";
      DataInputStream inStream = null;
      String boundary = Long.toHexString(System.currentTimeMillis()); // JustRandomValue
  
      String CRLF = "\r\n"; // Line separator required by multipart/form-data.
      String charset = "UTF-8";
      String urlString = "http://localhost:89/ImageUploaderv3/ImageUploadServlet";
  
      URLConnection connection = new URL(urlString).openConnection();
      connection.setDoOutput(true);// it is to indicate post method call
      connection.setRequestProperty("Content-Type",
              "multipart/form-data; boundary=" + boundary);
      PrintWriter writer = null;
  
      try {
          OutputStream output = connection.getOutputStream();
          writer = new PrintWriter(new OutputStreamWriter(output, charset),
                  true); // true = autoFlush, important!
  
          // Send normal param.
          writer.append("--" + boundary).append(CRLF);
          writer.append("Content-Disposition: form-data; name=\"param\"")
                  .append(CRLF);
          writer.append("Content-Type: text/plain; charset=" + charset)
                  .append(CRLF);
          writer.append(CRLF);
          writer.append(param).append(CRLF).flush();
  
          // Send binary file.
          writer.append("--" + boundary).append(CRLF);
          writer.append(
                  "Content-Disposition: form-data; name=\"binaryFile\"; filename=\""
                          + binaryFile.getName() + "\"").append(CRLF);
          writer.append(
                  "Content-Type: "
                          + URLConnection.guessContentTypeFromName(binaryFile
                                  .getName())).append(CRLF);
          writer.append("Content-Transfer-Encoding: binary").append(CRLF);
          writer.append(CRLF).flush();
          InputStream input = null;
          try {
              input = new FileInputStream(binaryFile);
              byte[] buffer = new byte[1024];
              for (int length = 0; (length = input.read(buffer)) &gt; 0;) {
                  output.write(buffer, 0, length);
              }
              output.flush(); // Important! Output cannot be closed. Close of
                              // writer will close output as well.
          } finally {
              if (input != null)
                  try {
                      input.close();
                  } catch (IOException logOrIgnore) {
                  }
          }
          writer.append(CRLF).flush(); // CRLF is important! It indicates end
                                          // of binary boundary.
          // End of multipart/form-data.
          writer.append("--" + boundary + "--").append(CRLF);
      } finally {
          if (writer != null)
              writer.close();
      }
      // ------------------ read the SERVER RESPONSE
  
      try {
          inStream = new DataInputStream(connection.getInputStream());
          String str;
          while ((str = inStream.readLine()) != null) {
              System.out.println("Server response is: " + str);
              System.out.println("");
          }
          inStream.close();
  
      } catch (IOException ioex) {
          System.out.println("From (ServerResponse): " + ioex);
  
      }
  
  }
  </code></pre>
  
  <p>}</p>
  
  <p>now i am trying to use commons-fileupload-1.2.2 and commons-io-2.4 jar for uploading image at server but how i can process the request i donot know . how to use use iterator of FileItem in this case ??
  code for servlet part is as follows.</p>
  
  <pre><code>class ImageUploadServlet extends HttpServlet {
  
  private boolean isMultipart;
  private String filePath;
  private int maxFileSize = 50 * 1024;
  private int maxMemSize = 4 * 1024;
  private File file;
  private String realpath;
  
  public void init() {
      // Get the file location where it would be stored.
      filePath = getServletContext().getInitParameter("file-upload");
      String h;
      h = getInitParameter("realpath");
      if (h != null) {
          realpath = h;
      }
      realpath = getServletConfig().getServletContext().getRealPath(realpath) + "/";
      System.err.println("realparh is  is =" + realpath);
  }
  
  //call post method 
  public void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, java.io.IOException {
  
      isMultipart = ServletFileUpload.isMultipartContent(request);
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      if (!isMultipart) {
          out.println("&lt;html&gt;");
          out.println("&lt;head&gt;");
          out.println("&lt;title&gt;Servlet upload&lt;/title&gt;");
          out.println("&lt;/head&gt;");
          out.println("&lt;body&gt;");
          out.println("&lt;p&gt;No file uploaded&lt;/p&gt;");
          out.println("&lt;/body&gt;");
          out.println("&lt;/html&gt;");
          return;
      }
  
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("F:\\Servers\\temp"));
  
      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax(maxFileSize);
  
      try {
          List&lt;FileItem&gt; fileItems = upload.parseRequest(request);
          ///how to process request here ...
          ///Image file send .....
  
  
  
      } catch (Exception ex) {
          System.out.println(ex);
      }
  
  
  
  }
  </code></pre>
  
  <p>}</p>
  
  <p>please help how to fill the code to process request and help me if i can do this in some other way .</p>