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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T23:12:17+00:00 2026-06-17T23:12:17+00:00

I can upload a file in a servlet using the apache commons FileUpload. The

  • 0

I can upload a file in a servlet using the apache commons FileUpload. The code below worked in the processRequest method off the servlet, but I copy Pasted the code in the doPost method and now it doesn’t work anymore. the line

 List fileItems = upload.parseRequest(request);

makes an empty array of fileItems.
How can this be?

Here is the full doPost method

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    int fileId = 0;

    String LogicalName = "";
    String PartNr = "";
    String Cost = "";
    String Assembly = "";
    String Comment = "";
    try {
        Connection conn = MysqlConnect.conn();
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {  //als het een veld is dan dit, anders File uploaden
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();
                switch (fieldname) {
                    case "logicalName":
                        LogicalName = fieldvalue;
                        break;
                    case "partNr":
                        PartNr = fieldvalue;
                        break;
                    case "cost":
                        Cost = fieldvalue;
                        break;
                    case "assembly":
                        Assembly = fieldvalue;
                        break;
                    case "comments":
                        Comment = fieldvalue;
                        break;

                }

            } else {
                PrintWriter out = response.getWriter();
                File file;
                int maxFileSize = 500000 * 1024;//max 500 mb groot
                int maxMemSize = 5000 * 1024;//max 5mb gecached in het ram,indien file groter is eerst wegschrijven in een temp dir

                String filePath = "C:\\uploads\\";
                String fileName = "";
                String contentType = request.getContentType();
                if ((contentType.indexOf("multipart/form-data") >= 0)) {

                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    factory.setSizeThreshold(maxMemSize);
                    factory.setRepository(new File("c:\\temp"));
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    upload.setSizeMax(maxFileSize);

                    try {
                        List fileItems = upload.parseRequest(request);
                        Iterator i = fileItems.iterator();

                        while (i.hasNext()) {
                            FileItem fi = (FileItem) i.next();
                            if (!fi.isFormField()) {
                                String fieldName = fi.getFieldName();
                                fileName = fi.getName();
                                boolean isInMemory = fi.isInMemory();
                                long sizeInBytes = fi.getSize();
                                if (fileName.lastIndexOf("\\") >= 0) {
                                    file = new File(filePath
                                            + fileName.substring(fileName.lastIndexOf("\\")));
                                } else {
                                    file = new File(filePath
                                            + fileName.substring(fileName.lastIndexOf("\\") + 1));
                                }
                                fi.write(file);
                            }
                        }





                        HttpSession session = request.getSession();


                        int uploader = (Integer) session.getAttribute("UserId");
                        String Query = "Insert into tbl_file (fileLocation,Uploader)values(\"" + fileName + "\"," + uploader + ");";
                        PreparedStatement st = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS);
                        st.executeUpdate();


                        ResultSet rs = st.getGeneratedKeys();
                        if (rs.next()) {
                            fileId = rs.getInt(1);
                        }


                    } catch (Exception ex) {
                        System.out.println(ex);
                    }
                }
            }
        }
        if (fileId == 0) {
            //ERROR
        } else {
            Statement stmt = conn.createStatement();
            String Query1 = "Insert into tbl_part (partCad,partCost,partAssembly,partMotivation,partOf) VALUES(" + fileId + "," + Cost + "," + Assembly + ",\"" + Comment + "\"," + "1" + ");";
            stmt.executeUpdate(Query1);
        }
        MysqlConnect.close(conn);
    } catch (SQLException ex) {
        Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    }
    String URL = "/home.jsp";
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(URL);
    dispatcher.forward(request, response);

}

And This is the JSP

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     
 "http://www.w3.org/TR/html4/loose.dtd">

 <html>
 <head>
 <title>File Uploading Form</title>
 </head>
 <body>
 <h3>File Upload:</h3>
 Select a file to upload: <br />
 <form action="/Racing/UploadServlet" method="post"
                    enctype="multipart/form-data">
 <input type="file" name="file"  />
 <br />
 Logische Naam: <input type="text" name="logicalName"><br>
 Stuknr(automatisch,nog niet geimplementeerd): <input type="text" name="partNr"><br>
 Kost: <input type="text" name="cost"><br>


 Assembly:
<select name = "assembly">
 <c:forEach var ="assembly" items="${Assemblys}">
  <option value="${assembly.id}">${assembly.name}</option>
 </c:forEach>
</select>
<br>
<textarea name="comments" cols="25" rows="5">
Verdediging Design
</textarea><br>

<input type="submit" value="Upload File" />

</form>
</body>
</html>

Many thanks in advance!

  • 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-17T23:12:19+00:00Added an answer on June 17, 2026 at 11:12 pm

    Your code line List fileItems = upload.parseRequest(request); and even all the lines in the else part doesn’t have any sense at all because:

    1. You already have processed the request before in this line

      List<FileItem> items = new ServletFileUpload(
          new DiskFileItemFactory()).parseRequest(request);
      

      No need to process the request again.

    2. You already have the file you want/need to process in the item object which isFormField method returns false.

    Change your method in order to look like here: How to upload files to server using JSP/Servlet?:

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);
    for (FileItem item : items) {
        if (item.isFormField()) {  //als het een veld is dan dit, anders File uploaden
            String fieldname = item.getFieldName();
            String fieldvalue = item.getString();
            switch (fieldname) {
                case "logicalName":
                    LogicalName = fieldvalue;
                    break;
                //other case statements...
            }
        } else {
            //here you only have to process the file
            File file;
            int maxFileSize = 500000 * 1024;//your comments...
            int maxMemSize = 5000 * 1024;//your comments...
            //this must be a constant or a servlet init param, do not hard code it
            String filePath = "C:\\uploads\\";
            String fileName = FilenameUtils.getName(item.getName());
            factory.setSizeThreshold(maxMemSize);
            //didn't you have a filePath variable?
            factory.setRepository(new File("c:\\temp"));
            upload.setSizeMax(maxFileSize);
            try {
                String fieldName = fi.getFieldName();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                file = new File(filePath, fileName);
                item.write(file);
                //code to save your file location in db...
                //note: this MUST BE in a business logic method, not directly written in your servlet
                HttpSession session = request.getSession();
                int uploader = (Integer) session.getAttribute("UserId");
            } catch (Exception ex) {
                //very BAD idea
                //use a logger instead like log4j or sfl4j
                System.out.println(ex);
            }
        }
    }
    

    Additional: check the File(String parent, String child) constructor.

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

Sidebar

Related Questions

I have implemented fileupload functionality using apache commons file upload library and implemented logic
I've written a Servlet that handles file uploads using the Apache commons file upload
I try to do a simple file upload to server using apache.fileupload. I tried
I can upload file in MVC3 (C#) by using HttpPostedFileBase but i want to
How can I upload a File (graphic, audio and video file) with Android using
How can one best test a controller action which receives a file upload using
I am using the jQuery-File-Upload widget (although I believe this question can generalize to
I've been doing research on image file upload security for a while but can't
trying to upload a file on a facelets page using Tomahawk2.0 1.1.11. But I
I am using jsp/servlet for file upload, i am able to upload a file

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.