5

I am trying to upload a csv file inside from a jsp page using a servlet that extends HttpServlet. Inside the jsp page I am using an ajax that should call the servlet.

This is the ajax part:

    $(function() {
    $(".upldBtn").click(function() {

        alert("Upload button pushed");

        $.ajax({
            type: "POST",
            url: contextPath + servletPath,
            data: "action=get&custIdList=" + $('#custIdList').val(),
            async: false,
            dataType: "text/csv; charset=utf-8", 
            success: function(data){
                  alert("success");
              }
        });
    });

The contextPath and servletPath are also declared, I didn't specified them here.

In the jsp page, I have this form inside a table :

<form method="post" action="CSRUploadListServlet" enctype="multipart/form-data">
<input type="file" name="custIdList" id="custIdList" />
<input type="submit" value="Upload" class="upldBtn" />
</form>

Inside the servlet, I want to use this doPost method:

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

    String methodName = "doPost";

    logger.debug("[{}] call", methodName);

    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        logger.debug("[{}] Request does not contain upload data",
                methodName);
        writer.flush();
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    logger.debug("[{}] factory= {} ", methodName, factory);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    logger.debug("[{}] upload= {} ", methodName, upload);

    // constructs the directory path to store upload file
    String uploadPath = getServletContext().getRealPath("")
            + File.separator + UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
        logger.debug("[{}] upload directory = {} ", methodName,
                uploadDir.mkdir());
    }

    try {
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);

                // saves the file on disk
                item.write(storeFile);
            }
        }
        request.setAttribute("message",
                "Upload has been done successfully!");
        logger.debug("[{}] Upload has been done successfully! ", methodName);
    } catch (Exception ex) {
        request.setAttribute("message",
                "There was an error: " + ex.getMessage());
        logger.debug("[{}] There was an error: {} ", methodName, ex);
    }
    getServletContext().getRequestDispatcher(
            "/WEB-INF/web/csrCustomerLists/message.jsp").forward(request,
            response);
}

All this gets stuck at if (!ServletFileUpload.isMultipartContent(request)), returning that: 'Request does not contain upload data'.

I am sure that I am not writing the ajax correctly, but I can't seem to find out where I am doing it wrong.

Thanks.

4
  • when you are pressing submit button then CSRUploadListServlet and contextPath + servletPath are called,May I know why? Commented Nov 18, 2013 at 16:22
  • yes, in order to use the servlet when i push the upload submit button. Commented Nov 18, 2013 at 16:56
  • You can't upload a file via Ajax like this. You are treating the file like a normal parameter. That won't work. See stackoverflow.com/questions/1686099/… Commented Nov 18, 2013 at 21:32
  • Okay, I can see that now, thank you. But if I avoid using Ajax the form is not being accessed through the servlet Commented Nov 19, 2013 at 8:47

1 Answer 1

4

Hei! Try to put your html code differently, and then call the servlet from ajax, just the way you did there. I think the problem may be in the form you are using, that is rewriting some attributes or something like that.

I suggest an option with an iframe, loaded from the js code.The html code can be like this:

<button id="upldBtn" title="Upload" >Do the upload</button>

<div id="textarea" style="display: none;"></div>

<input type="file" class="file" id="file" name="file" title="Please upload"/>

And the javascript code:

    $(function() { 

    $('#upldBtn').click(function() {
        var contextPath = 'your path string';
        var servletName = 'your servlet name string';
        var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none" />');
        $("body").append(iframe);

         $("form#yourform").attr('action', contextPath+servletName);
         $("form#yourform").attr('enctype', "multipart/form-data");
         $("form#yourform").attr("target", "postiframe");
         $("form#yourform").attr("file", $('#file').val());

        $('yourform').submit(); //upload button 
             $("#postiframe").load(function () {
                    iframeContents = $("#postiframe")[0].contentWindow.document.body.innerHTML;
                    $("#textarea").html(iframeContents);
                            $.ajax({
                                    type: "GET",
                                    url: contextPath+servletName,
                                    data: "action=download",
                                    async: false,
                                    dataType: "text",
                                    success: function(result) {
                                        //do something
                                    }
                                });
                } });
            }); 
});

Tell me if it is ok for you. :) Cheers

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.