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

  • SEARCH
  • Home
  • 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 4238214
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T02:52:31+00:00 2026-05-21T02:52:31+00:00

I need to upload an image. For that I have to pass an image

  • 0

I need to upload an image. For that I have to pass an image and an ID to the server.

dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
            + fileName + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + stringFieldName + "\""+ lineEnd);
dos.writeBytes(lineEnd);

fileName is the image path.
stringFieldName is the user_id

My code is given below.

public void webservicePhp(Long userId, Bitmap bmp) {
    String userIdParameter = String.valueOf(userId);
    String fileName = "temporary_holder.jpg";
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    String charset = "UTF-8";
    String responseFromServer = "";

    String stringFieldName = "user_id";

    String sourceFileUri = HomeScreen.get_path();
    String upLoadServerUri = "http://10.120.10.87:8080/ContactsManagerWeb/UploadImage";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.e("Huzza", "Source File Does not exist");
        return;
    }
    int serverResponseCode = 0;
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
                                     // connection to
                                     // the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Accept-Charset", charset);

        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("file_name", fileName);
        conn.setRequestProperty("user_id", userIdParameter);
        dos = new DataOutputStream(conn.getOutputStream());
        dos.write(query.getBytes(charset));
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
                + fileName + "\"" + lineEnd);

        dos.writeBytes("Content-Disposition: form-data; name=\"" + stringFieldName + "\""+ lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
        bufferSize = (int) sourceFile.length();

        System.out.println("BytesAvail" + bytesAvailable);
        System.out.println("maxBufferSize" + maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        System.out.println("Upload file to serverHTTP Response is : "
                + serverResponseMessage + ": " + serverResponseCode);
        // close streams
        System.out.println("Upload file to server"+ fileName + " File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // this block will give the response of upload link
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            System.out.println("RESULT Message: " + line);
        }
        rd.close();
    } catch (IOException ioex) {
        Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
    }
    return; // like 200 (Ok)
}

In my servlet I am not able to access the user_id parameter. It’s not getting there.

Servlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    File filenameImg = null;
    List<FileItem> items = null;
    try {
        items = new ServletFileUpload(new DiskFileItemFactory())
                    .parseRequest(request);
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    }

    for (FileItem item : items) {
        if (item.isFormField()) {
            // Process regular form fields here the same way as
            // request.getParameter().
            // You can get parameter name by

            String fieldname = item.getFieldName();
            String fieldvalue = item.getString(); 
            System.out.println("user_id===fieldname====== "+fieldname);
            System.out.println("user_id====fieldvalue===== "+fieldvalue);
            // You can get parameter value by item.getString();
        } else {
            try{
                // Process uploaded fields here.
                String filename = FilenameUtils.getName(item.getName());
                // Get filename.
                String path = GetWebApplicationPathServlet.getContext().getRealPath("/images");

                File file = new File(path,filename);

                // Define destination file.
                item.write(file);
                System.out.println("filename: "+filename);
                System.out.println("file: "+file);
                request.setAttribute("image", file);
                filenameImg = file;
                // Write to destination file.
                //    request.setAttribute("image", filename);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    // Show result page.
    System.out.println("request"+request.getAttribute("image"));
    //response.setContentType("image/jpeg"); 
    request.setAttribute("servletName", filenameImg);
    getServletConfig().getServletContext().getRequestDispatcher(
        "/result.jsp").forward(request,response);
}

if (item.isFormField()) {} is returning false.

Please help.

  • 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-05-21T02:52:32+00:00Added an answer on May 21, 2026 at 2:52 am

    If this is same with html form submit. Then you can try this.

    In your if (item.isFormField()) { in your Servlets do this.

    String user_Id = null; //Create an instance of String variable before initializing (Optional)
    
    if (item.isFormField()) {
        if(item.getFieldName().contentEquals("name")){  //Check if the item in the loop is the user_id
             user_id = item.getString();                //If yes store the value
        }
    } else { //continue with your current code
    

    I run with the same problem before and this is the one worked for me. I’m not sure if this what you looking for, just have a try.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to upload an image to my server under a specific name, but
I have an image upload form that takes a title and a file for
I need to upload an image to a remote PHP server which expects the
I need to upload a single image to server. The project is using .NET
I need to upload a given image using Amazon S3 I have this PHP:
I have a byte[] of an image and I need to upload it as
I have a ajax image upload script which i found here http://www.fengcool.com/2009/06/ajax-form-upload-local-image-file-without-refresh/ The problem
I need to upload image to the server, where SmartGWT webapplication is running... after
I need to upload a pic on server without using html form tag. Is
I need to upload a single image to server. The project is using .NET

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.