2

The action EdgeWarUpload in the below form is a servlet and it is to upload a file.

<form action="EdgeWarUpload" method="post"
                    enctype="multipart/form-data">
    <input type="file" name="file" size="50" />
        <br />
     <input type="submit" value="Upload File" />
 </form>

It is working fine but inside the servlet post method , I want the name of the file that is uploaded.I tried with

request.getParameter("file");

But that is giving me null. How can I get the value of the file name from the form.Please check.

user1281029
  • 1,513
  • 8
  • 22
  • 32

1 Answers1

4

For Servlet 3.0 API

Add @MultipartConfig() to the servlet and use this to print the names.

public void printNames(HttpServletRequest request){
    for(Part part : request.getParts()){
        System.out.println("PN: "+ part.getName());
        Collection<String> headers = part.getHeaders("content-disposition")
        if (headers == null)
            continue;
        for(String header : headers){
            System.out.println("CDH: " + header);                  
        } 
    }
}

For older Servlet APIs I would recommend to use Apache Commons FileUpload

Balint Bako
  • 2,500
  • 1
  • 14
  • 13
  • Hi @Balint Bako I got the name of the parameter as "file".But I want the value of the parameter.I mean the name of the file that I selected for upload. – user1281029 Jun 20 '13 at 13:11
  • I see, sorry about that, I didn't launch a servlet to test it. Check the `part.getHeaderNames()` and the header values, it should be in it. It should be in the `Content-Disposition` header actually. – Balint Bako Jun 20 '13 at 13:14
  • part.getHeaderNames() contains two items.content-type and content-disposition. – user1281029 Jun 20 '13 at 13:39
  • As I wrote ´content-disposition´ should be the name. Get the value of the header value with `part.getHeaders("content-disposition")`. I've updated the answer. – Balint Bako Jun 20 '13 at 13:41