3

I am trying to upload a file using JSP and servlet. Here is the JSP code :

 <script type="text/javascript">
 function UploadFile() {
    var paramater = "hello";
    $.post('fileUploadServlet', {param : paramater});
}
</script>
<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="datafile" size="50" /> <br /> 
    <input type="submit" value="Upload File" onclick="UploadFile()" />
    <input type="hidden" name="type" value="upload">
</form>

The servlet code is shown below :

public class fileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static final String DATA_DIRECTORY = "data";
private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
private static final int MAX_REQUEST_SIZE = 1024 * 1024;

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // Check that we have a file upload request
    System.out.println(request.getContentType());
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;
    }

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

    // Sets the size threshold beyond which files are written directly
    // to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are
    // larger
    // than the configured size threshold. We use temporary directory
    // for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    // String uploadFolder = System.getProperty("java.io.tmpdir") +
    // File.separator + UUID.randomUUID().toString() + File.separator +
    // "abc.xml";
    // FileUtils.createFileParent(uploadFolder);

    // constructs the folder where uploaded file will be stored
    String uploadFolder = "C:\\Users\\IBM_ADMIN\\workspace_new\\Trees\\WebContent\\UploadedFiles";

    // String uploadFolder = getServletContext().getRealPath("")
    // + File.separator + DATA_DIRECTORY;

    System.out.println("uploadFolder : " + uploadFolder);

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

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);

    try {
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();

                String filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                item.write(uploadedFile);
                response.getWriter().write("Work done");
            }
        }

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}

}

When I debug, I observed that it fails at the line if(!isMultipart) and the servlet returns and fails to upload any file. I tried to print the request.getContentType(), it prints as application/x-www-form-urlencoded; charset=UTF-8 instead of multipart/form-data. Where am I going wrong?

Thanks in advance!

Ravz
  • 43
  • 7

2 Answers2

0

Add following lines of code before you define your Servlet, to handle multipart/form-data submissions you have to use Multipart annotation

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;

@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB maxFileSize = 1024 * 1024 * 10, // 10MB maxRequestSize = 1024 * 1024 * 50)

@WebServlet("/ServletName")

Deepika Rajani
  • 564
  • 5
  • 15
0

if your using Servlet 3.0, you can use "Part" class to get the multi part content. Multi part encodes all the content within that form, to use those thing you first have to decrypt them.

Sagar Rout
  • 651
  • 1
  • 12
  • 29