1

Possible Duplicate:
How to upload files in JSP/Servlet?

I have to pass a text file as input in jsp file and read the contents of a file in servlet. I don't know which method to use in servlet to read the file. For example to read a text input we use request.getParamater() method in servlet. I don't know how to read a file input.In jsp I have the following code

 <form action="load" method="post" enctype="multipart/form-data">
 Select a file to upload:<input type="file" name="filename" size="20"/><br><br>
 <input type="submit" value="Upload File"/>
 </form>

How to get the file in servlet and read the contents?

Community
  • 1
  • 1
Learner
  • 43
  • 1
  • 2
  • 10

1 Answers1

1

You need to use the commons-fileupload library to load the file in the servlet. Here's an example from the documentation:

// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Parse the request
List /* FileItem */ items = upload.parseRequest(request);

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

    if (item.isFormField()) {
        processFormField(item);
    } else {
        processUploadedFile(item);
    }
}
MaurĂ­cio Linhares
  • 39,901
  • 14
  • 121
  • 158