Search code examples
javascriptajaxspringjspform-data

Sending a File (PDF) through ajax to a JSP Servlet


I am trying to send two PDF Files )initially just one) through an HTML form using javascript (jquery or not), I have to receive both files in a controller of a JSP page (using Spring) and do something with both files.

Right now I have been trying some of the answers already posted here in SO, but I am not being able to get it to work correctly.

My HTML File

<form id="searchForm">
                <table class=rightAlignColumns>
                    <tr>
                        <td><label for="File1"><spring:message code='File1' />:</label></td>
                        <td><input id="File1" type="file" name="File1" /> </td>

                        <td><label for="file2"><spring:message code='File2' />:</label></td>
                        <td><input id="file2" type="file" name="file2" /> </td>
                    </tr>   
                </table>
                    <br/>
                    <input type="submit" value="<spring:message code='Btn' />" />
            </form>

My javascript

var fd = new FormData();    
    alert(document.getElementById('File1').files.length);
    fd.append( 'File1', document.getElementById('File1').files[0] );
//  fd.append( 'File2', document.getElementById('File2').files[0]);
    $.ajax({
    url:'myurl.json',
      data: fd,
      cache:false,
        processData:false,
        contentType:false,
      type: 'POST',
      success: function(data){
//      alert(data);
      }
    });

On the controller I am doing what this other post said.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                String fieldName = item.getFieldName();
                String fieldValue = item.getString();
                // ... (do your job here)
            } else {
                // Process form file field (input type="file").
                String fieldName = item.getFieldName();
                String fileName = FilenameUtils.getName(item.getName());
                InputStream fileContent = item.getInputStream();
                // ... (do your job here)
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    }

    // ...
}

The problem I think it is in the javascript, because when the code enters to the Controller the list "items" has a size of 0, and going into the exception.

The expected result would be the user loading a PDF file into the Form, hitting submit and ajax sending the file to the server (controller), doing stuff correctly and sending back a result.

Right now the client is not uploading correctly the file.

As a side note, the file I am uploading is going to be used by pdfbox or google ocr in the controller.

Thanks in advance!


Solution

  • It worked using the next code:

    JS: function doAjax() {

    // Get form
    var form = $('#id_form')[0];
    var data = new FormData(form);
    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "controller/myMethod",
        data: data,
        processData: false, //prevent jQuery from automatically transforming the data into a query string
        contentType: false,
        cache: false,
        dataType:'json',
        success: function (e) {
            $("#result").text(data);
            alert("Success");
        },
        error: function (e) {
            $("#result").text(e.responseText);
            alert("Error");
        },
        complete: function () {
            // Handle the complete event
            alert("Complete");
          }
    });
    }
    

    And on the controller

    @RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
    public String uploadFileMulti(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        try {
            //storageService.store(file, request);
            System.out.println(file.getOriginalFilename());
            return "You successfully uploaded " + file.getOriginalFilename();
        } catch (Exception e) {
            return "FAIL!";
        }
    }
    

    My HTML file

     <form class="form-horizontal" method="POST" enctype="multipart/form-data" id="id_form">
        <label for="file">File:</label>
        <input id="file" type="file" name="file" />
    </form>