Uploading file with JSP, servlet and ajax without setting form action attribute

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 noticed that it doesn't work on the if (! IsMultipart) line and the servlet comes back and can't load any file. I tried to print 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!

+3


source to share


2 answers


Add the following lines of code before defining your servlet to handle the multipart / form-data views you must use the 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")

0


source


if you are using Servlet 3.0, you can use the Part class to get the content of multiple parts. The multi-part encodes all content in this form in order to use the things you first need to decode them.



0


source







All Articles