Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form parameters not passing but File in the same form processed? [duplicate]

I have a webform on JSP which has several string values and a file to uploaded to the server through a servlet. It is strange to see that I'm able to upload the file on to the server but not able to get the values in the servlet using request.getParameter("someString").

What's the problem with my code, or guide me?

EDIT: With a bit of research, i have come to know that if i use enctype="multipart/form-data" in the form tag, i will not be able to get parameters in servlet using request.getParameter(). The question could be now, how can i send both a file and other values to a servlet for processing.

webform.jsp:

<form method="POST"  enctype="multipart/form-data" action="/cassino/uploadFile" >
    <fieldset>
            <div class="form-group">
                <label >*ID riparazione</label>

                    <input type="text" name="idRiparazione"  />
            </div>
            <div class="form-group">
                <label>*ID mandrino smontato</label>

                    <input type="text" name="idMandrinoSmontato" />
            </div>
            <div class="form-group">
                <label>*Service livello(SL)</label>
                <input type="text" name="serviceLivello" />
            </div>
                <div class="form-group">
                <label>Attachment</label>
                    <input type="file" name="attachment" class="" id="attach" />
                 </div>
            </fieldset>
        </div>
        <p class="text-right">
            <input type="submit" value="Salva"  name="newMacchina" /> 
            <input type="reset" value="Cancella" />
        </p>
    </form>

And uploadFile.java

@WebServlet( name = "uploadFile", urlPatterns = { "/uploadFile" } )
public class uploadFile extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final int THRESHOLD_SIZE = 1024 * 1024 * 3;
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 15;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 20;

    /**
     * handles file upload via HTTP POST method
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // checks if the request actually contains upload file
        //ServletFileUpload.isMultipartContent(request);

        String idRiparazione = request.getParameter("idRiparazione");
        String idMandrinoSmontato = request.getParameter("idMandrinoSmontato");
        String serviceLivello = request.getParameter("serviceLivello");

        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>Hello Servlet Get</h1>");
        out.println(idMandrinoSmontato);
        out.println(serviceLivello);
        out.println("</body>");
        out.println("</html>"); 

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(THRESHOLD_SIZE);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // constructs the directory path to store upload file
        String uploadPath = "C:\\SKFSFCassino\\uploads\\riparazione\\";  //getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
        // creates the directory if it does not exist
        File uploaddir = new File(uploadPath);
        if( !uploaddir.exists()) {
            uploaddir.mkdirs();
        }

        try {
            List formItems = upload.parseRequest(request);
            Iterator it = formItems.iterator();
            // iterates over form's fields
            while(it.hasNext()) {
                FileItem item = (FileItem) it.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);
                    // saves the file on disk
                    item.write(storeFile);
                }
            }
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // response.sendRedirect(request.getContextPath()+"/modules/SKFsfRepair/new/viewNewContent.jsp");

    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
        throw new ServletException("GET method used with " + getClass().getName() + ": POST method required.");
    }

I don't think there could be a problem with the mapping but I am slightly confused about this too because my web.xml is not showing any mapping or servlet. The servlet would, however, upload the file and return the following output:

Hello Servlet Get

null null
like image 843
fresh learner Avatar asked Sep 30 '22 21:09

fresh learner


1 Answers

You're correct that you can no longer use request.getParameter() in this situation with the multipart form. FileUpload provides access to your non-file form fields through the FileItem class. As you iterate over the items, check the field names against the names you're looking for.

    ...
    String idRiparazione = null;
    String idMandrinoSmontato = null;
    String serviceLivello = null;

    try {
        List formItems = upload.parseRequest(request);
        Iterator it = formItems.iterator();
        // iterates over form's fields
        while(it.hasNext()) {
            FileItem item = (FileItem) it.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);
                // saves the file on disk
                item.write(storeFile);
            }
            else
            {
                if ("idRiparazione".equals(item.getFieldName()))
                    idRiparazione = item.getString();
                else if ("idMandrinoSmontato".equals(item.getFieldName()))
                    idMandrinoSmontato = item.getString();
                else if ("serviceLivello".equals(item.getFieldName()))
                    serviceLivello = item.getString();
            }
        }

        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>Hello Servlet Get</h1>");
        out.println(idMandrinoSmontato);
        out.println(serviceLivello);
        out.println("</body>");
        out.println("</html>");             
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
like image 83
Tap Avatar answered Oct 06 '22 01:10

Tap