Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8389453
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T18:43:51+00:00 2026-06-09T18:43:51+00:00

i have to upload an image on server using servlet and request to servlet

  • 0

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:

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

    }

}

}

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.

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("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        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<FileItem> fileItems = upload.parseRequest(request);
        ///how to process request here ...
        ///Image file send .....



    } catch (Exception ex) {
        System.out.println(ex);
    }



}

}

please help how to fill the code to process request and help me if i can do this in some other way .

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T18:43:53+00:00Added an answer on June 9, 2026 at 6:43 pm

    This is the way:

    // Process the uploaded items
    
    Iterator iter = items.iterator();
    
    while (iter.hasNext()) {
    
      FileItem item = (FileItem) iter.next();
    
      if (item.isFormField()) {
    
        processFormField(item);
      } else {
    
        processUploadedFile(item);
      }
    }
    

    See:

    • http://commons.apache.org/fileupload/apidocs/org/apache/commons/fileupload/FileItem.html
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have to upload my image using HTTP Post request. Image will be posted
I have implemented the image upload code using jquery php in my php web
I wanted to upload a jpeg image file on the server.I have a GoAhead
I have tried to upload image using FileTransfer.upload in phonegap api.But I am getting
I have added multiple image upload to my site using HTML api's. I have
After research I have figured out how to upload an image to my server
I'm trying to upload an image from android to a PHP server by using
I need to upload a single image to server. The project is using .NET
I simply want to upload an image to a server with POST. As simple
I have a problem to upload an image using Symfony. I have a form

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.