Question

The following HTML snippet makes a POST request to a servlet SendFileName.

<form method="post" action="SendTheFileName" enctype="multipart/form-data">
                <div id="Files_to_be_shared"> 
                      <input type="file" id="File" name="FileTag" />
                      <input type="submit" value="Share" /> 
                </div>
</form>

In the servlet's POST method I try to get the file name by calling :

String FileName = request.getParameter("FileTag")

but I am getting null. Why is that ?

I am using Apache commons for file upload. It is working fine. I don't know why do I get null when the enctype is multipart/form-data while using only the jdk.

Était-ce utile?

La solution

Servlet 3.0 API (Java EE 6) provides methods to access the content of a multipart post:

See HttpServletRequest.getParts() You should have one Part for the file and one for each parameter.

Autres conseils

When you use enctype="multipart/form-data", all the form parameters are transferred as multipart.

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);

// Process the uploaded form items
Iterator iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();

    if (item.isFormField()) {
       // ** here you get the non-file parameters **
    } else {
        processUploadedFile(item);
    }
}

Your are getting null because when form is entype of "multipart/form-data" and your input type is "file" it won't go inside HttpServletRequest requestParameterMap().

You have to use another option from Java EE 6 like this:

Part filePart = request.getPart("FileTag"); // or "File" - I am not sure 
                                            // that not for id value 
                                            // you should search
String fileName = filePart.getName();

Also if you can use JSF not just Jave EE Servlets there (in JSF 2.2) are special tag for input type="file":

<h:inputFile value="#{myFileUploader.file}"/>


This should help.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top