0

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!

Manzha
  • 65
  • 1
  • 3
  • 11
  • In your HTML form `method="post" enctype="multipart/form-data"` data(s) were missing. – Vinoth Krishnan Dec 05 '17 at 03:38
  • I just tried that and it didn't work well. It tried to make a post refreshing the whole page and sent an error. – Manzha Dec 05 '17 at 21:48
  • Nevermind, I did something wrong the first time. It just works the same, not able to receive the data correctly. When it comes to the for(Fileitem item:items) something goes wrong and it catch the exception. – Manzha Dec 05 '17 at 22:15
  • Just check whether your request contains multi-part data. Post your updated code and error stacktrace – Vinoth Krishnan Dec 14 '17 at 07:14
  • Where should I check for multi-part data, jsp or js? – Manzha Dec 15 '17 at 18:18
  • I think I already made it work! I'll check and try to post the answer tomorrow. Thanks for your comments. – Manzha Dec 20 '17 at 02:11

1 Answers1

1

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>
Manzha
  • 65
  • 1
  • 3
  • 11