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 7826235
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T09:18:48+00:00 2026-06-02T09:18:48+00:00

I am learning java servlet programming and I wrote a program to upload files,

  • 0

I am learning java servlet programming and I wrote a program to upload files, I’m having a strange problem with the program. when it says it finished uploading the file and when i click the link to see it I get a 404 error and when i check the directory (where the file is supposed to be saved ) its empty. I checked the log and there are no error messages.I got the code from a book I’m using to learn servlet and jsp.

here is my java code

import java.io.*;
import java.util.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FileUpload
 */
@WebServlet("/FileUpload")
public class FileUpload extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileUpload() {
        super();
        // TODO Auto-generated constructor stub
    }


    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.print("File upload success. <a href=\"/Project_One/files");
        out.print("\">Click here to browse through all uploaded ");
        out.println("files.</a><br>");

        ServletInputStream sis = request.getInputStream();
        StringWriter sw = new StringWriter();
        int i = sis.read();
        for(;i!=-1 && i!= '\r';i=sis.read())
            {
                sw.write(i);
            }
        sis.read(); //ditch \'n'
        String delimiter = sw.toString();


        while(true)
            {
                StringWriter h = new StringWriter();
                int[] temp = new int[4];
                temp[0] = (byte)sis.read();
                temp[1] = (byte)sis.read();
                temp[2] = (byte)sis.read();
                h.write(temp[0]);
                h.write(temp[1]);
                h.write(temp[2]);

                //read header
                for(temp[3]=sis.read();temp[3]!=-1;temp[3]=sis.read())
                    {
                        if(temp[0] == '\r' &&
                           temp[1] == '\n' &&
                           temp[2] == 'r'  &&
                           temp[3] == '\n')
                            {
                                break;
                            }

                        h.write(temp[3]);
                        temp[0]= temp[1];
                        temp[1]= temp[2];
                        temp[2]= temp[3];   
                    }
                String header = h.toString();

                int StartName = header.indexOf("name=\"");
                int endName = header.indexOf("\"",StartName+6);
                if(StartName == -1|| endName == -1)
                    {
                        break;
                    }
                String name = header.substring(StartName+6,endName);
                if(name.equals("file"))
                    {
                        StartName = header.indexOf("filename=\"");
                        endName = header.indexOf("\"",StartName+10);
                        String filename = header.substring(StartName+10,endName);
                        ServletConfig config = getServletConfig();
                        ServletContext sc = config.getServletContext();

                        //File file = new File(sc.getRealPath("/files"));
                        //file.mkdirs();
                        FileOutputStream fos = new FileOutputStream(sc.getRealPath("/")+"/"+filename);

                        //write the file to disk 
                        int length = delimiter.length();
                        //delimiter ="\r\n"+delimiter;
                        byte[] body = new byte[delimiter.length()];
                        for(int j=0;j<body.length-1;j++)
                            {
                                body[j]=(byte)sis.read();
                                fos.write(body[j]);
                            }

                        //check it wasn't a 0 length file
                        //if(!delimiter.equals(new String (body)))
                            //{
                                int e = body.length-1;
                                i=sis.read();
                                for(;i!=-1;i=sis.read())
                                    {
                                        body[e]=(byte)i;
                                        /*fos.write(body[0]);
                                        for(int l=0;l<body.length-1;l++)
                                            {
                                                body[l]=body[l+1];
                                            }*/
                                        //body[e]=(byte)i;

                                        if(delimiter.equals(new String (body)))
                                            {
                                                break;
                                            }
                                        //length++;
                                        fos.write(body[e]);
                                        for(int k=0;k<body.length-1;k++)
                                            {
                                                body[k]=body[k+1];

                                            }
                                        length++;
                                    }

                        fos.flush();
                        fos.close();
                        out.println("<p><b>Saved File:</b>"+filename+"</p>");
                        out.println("<p><b>Length:</b>"+ length+"</p>");
                    }
                if(sis.read() == '-' && sis.read()=='-')
                    {
                        break;
                    }

                    }
        out.println("</html>");


            }



    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request,response);
    }



}

There were few changes made in the code , the changes were given in the book.
here is my HTML code

<html>
    <head>
        <title>Test HTML Form</title>
    </head>
    <body>
    <p>Select a file to upload or <a href="/Project_One/files/">browse currently uploaded files.</a></p>
    <form action="http://127.0.0.1/Project_One/FileUpload"
          method="post" enctype="multipart/form-data">
          File:<input type="file" name:"file"><br>
          <input value="Upload File" type="submit">
    </form>
    </body>
</html>

I’m using TomCat sever for this.

  • 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-02T09:18:50+00:00Added an answer on June 2, 2026 at 9:18 am

    Where did you get this code from? From a decade old servlet tutorial/book? This is all unnecessarily overcomplicated. Please make sure that you’re reading an up to date tutorial/book which is no older than one year.

    Here’s how the file upload could be done with the standard servlet 3.0 API:

    @MultipartConfig
    @WebServlet("/FileUpload")
    public class FileUpload extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        @Override    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
            String filename = getFilename(filePart);
            InputStream filecontent = filePart.getInputStream();
            // ... (do your job here)
        }
    
        private static String getFilename(Part part) {
            for (String cd : part.getHeader("content-disposition").split(";")) {
                if (cd.trim().startsWith("filename")) {
                    String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                    return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
                }
            }
            return null;
        }
    
    }
    

    That’s all. It also takes into account that the proper filename is returned. Some browsers such as MSIE namely incorrectly includes the full client side path along the filename. That might be the cause of your problem.

    Further there are 2 other problems not directly related:

    1. You should not store the uploaded file in the deploy folder. It will get lost whenever you redeploy the webapp. Store the file in a fixed path somewhere outside the deploy folder. See also for example How I save and retrieve an image on my server in a java webapp.

    2. You should be delegating the job of generating HTML to JSP. In the end of doPost(), forward the request to a JSP:

      request.getRequestDispatcher("/WEB-INF/uploadresult.jsp").forward(request, response);
      

    See also:

    • Our Servlets wiki page – contains hello world examples how to use servlets properly
    • How to upload files to server using JSP/Servlet?
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Im learning Java and having a problem with ArrayList. Firstly I have a class
I'm just learning java and following a book. I have a program written via
I'm currently learning Java EE, or more specifically, Servlets and .jsp. In my programming,
I'm learning Java Servlets and the book I'm using has an example on file
I am learning both AJAX and the Java Servlet API (well, Spring MVC, which
Possible Duplicate: servlet vs filter I am java beginner. Now I am learning about
I'm learning Java's generic, I snag into some problem instantiating the type received from
When I was learning Java coming from a background of some 20 years of
I am learning Java for a test (tomorrow) and am wondering about a question
So I'm learning java, and I have a question. It seems that the types

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.