How can I upload files to a server using JSP/Servlet and Ajax?
Asked Answered
H

4

19

I'm creating a JSP/Servlet web application and I'd like to upload a file to a servlet via Ajax. How would I go about doing this? I'm using jQuery.

I've done so far:

<form class="upload-box">
    <input type="file" id="file" name="file1" />
    <span id="upload-error" class="error" />
    <input type="submit" id="upload-button" value="upload" />
</form>

With this jQuery:

$(document).on("#upload-button", "click", function() {
    $.ajax({
        type: "POST",
        url: "/Upload",
        async: true,
        data: $(".upload-box").serialize(),
        contentType: "multipart/form-data",
        processData: false,
        success: function(msg) {
            alert("File has been uploaded successfully");
        },
        error:function(msg) {
            $("#upload-error").html("Couldn't upload file");
        }
    });
});

However, it doesn't appear to send the file contents.

Hollington answered 2/8, 2011 at 15:1 Comment(2)
Hope this will help you out: http://www.webdeveloperjuice.com/2010/02/13/7-trusted-ajax-file-upload-plugins-using-jquery/Balas
You can use XMLHttpRequest method. Look this: stackoverflow.com/questions/6974684/…Unveil
A
23

To the point, as of the current XMLHttpRequest version 1 as used by jQuery, it is not possible to upload files using JavaScript through XMLHttpRequest. The common workaround is to let JavaScript create a hidden <iframe> and submit the form to it instead so that the impression is created that it happens asynchronously. That's also exactly what the majority of the jQuery file upload plugins are doing, such as the jQuery Form plugin (an example).

Assuming that your JSP with the HTML form is rewritten in such way so that it's not broken when the client has JavaScript disabled (as you have now...), like below:

<form id="upload-form" class="upload-box" action="/Upload" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="file1" />
    <span id="upload-error" class="error">${uploadError}</span>
    <input type="submit" id="upload-button" value="upload" />
</form>

Then it's, with the help of the jQuery Form plugin, just a matter of

<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
    $(function() {
        $('#upload-form').ajaxForm({
            success: function(msg) {
                alert("File has been uploaded successfully");
            },
            error: function(msg) {
                $("#upload-error").text("Couldn't upload file");
            }
        });
    });
</script>

As to the servlet side, no special stuff needs to be done here. Just implement it exactly the same way as you would do when not using Ajax: How can I upload files to a server using JSP/Servlet?

You'll only need an additional check in the servlet if the X-Requested-With header equals XMLHttpRequest or not, so that you know how what kind of response to return for the case that the client has JavaScript disabled (as of now, it is mostly the older mobile browsers which have JavaScript disabled).

if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
    // Return an Ajax response (e.g. write JSON or XML).
} else {
    // Return a regular response (e.g. forward to JSP).
}

Note that the relatively new XMLHttpRequest version 2 is capable of sending a selected file using the new File and FormData APIs. See also HTML5 drag and drop file upload to Java Servlet and Send a file as multipart through XMLHttpRequest.

Adlay answered 2/8, 2011 at 18:9 Comment(3)
@Adlay any idea about XMLHttpRequest version 1 ? I mean where new FormData() dont work.. see developer.mozilla.org/en-US/docs/Web/API/…Schaub
@Adlay I got your point :).. ah let me come to the point.. I was using same plugin for IE 8 and 9 but no response, it says NO Transport.. any idea ?Schaub
@Derek: marc_s didn't post anything. If you're referring to the answer of Sameera Madushanka, then please be aware that he has posted a jurassic approach. His approach is not necessary anymore since 2009 (a decade ago!). The link in my answer titled "How to upload files to server using JSP/Servlet?" shows the most recent approach using HttpServletRequest#getParts(). Next time, please read the text and the links around the code snippets in answers as well before you miss out important information.Adlay
I
5

Monsif's code works well if the form has only file type inputs. If there are some other inputs other than the file type, then they get lost. So, instead of copying each form data and appending them to FormData object, the original form itself can be given to the constructor.

<script type="text/javascript">
        var files = null; // when files input changes this will be initialised.
        $(function() {
            $('#form2Submit').on('submit', uploadFile);
    });

        function uploadFile(event) {
            event.stopPropagation();
            event.preventDefault();
            //var files = files;
            var form = document.getElementById('form2Submit');
            var data = new FormData(form);
            postFilesData(data);
}

        function postFilesData(data) {
            $.ajax({
                url :  'yourUrl',
                type : 'POST',
                data : data,
                cache : false,
                dataType : 'json',
                processData : false,
                contentType : false,
                success : function(data, textStatus, jqXHR) {
                    alert(data);
                },
                error : function(jqXHR, textStatus, errorThrown) {
                    alert('ERRORS: ' + textStatus);
                }
            });
        }
</script>

The HTML code can be something like following:

<form id ="form2Submit" action="yourUrl">
  First name:<br>
  <input type="text" name="firstname" value="Mickey">
  <br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse">
  <br>
<input id="fileSelect" name="fileSelect[]" type="file" multiple accept=".xml,txt">
<br>
  <input type="submit" value="Submit">
</form>
Infielder answered 11/10, 2016 at 16:36 Comment(2)
The link is broken: "Page Not Found"Paraglider
The dead link is being removed.Infielder
F
2

$('#fileUploader').on('change', uploadFile);


function uploadFile(event)
    {
        event.stopPropagation(); 
        event.preventDefault(); 
        var files = event.target.files; 
        var data = new FormData();
        $.each(files, function(key, value)
        {
            data.append(key, value);
        });
        postFilesData(data); 
     }
    
function postFilesData(data)
    {
     $.ajax({
        url: 'yourUrl',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, 
        contentType: false, 
        success: function(data, textStatus, jqXHR)
        {
            //success
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            console.log('ERRORS: ' + textStatus);
        }
        });
    }
<form method="POST" enctype="multipart/form-data">
    <input type="file" name="file" id="fileUploader"/>
</form>
Forme answered 24/11, 2015 at 13:56 Comment(0)
F
0

This code works for me.

I used Commons IO's io.jar, Commons file upload.jar, and the jQuery form plugin:

<script>
    $(function() {
        $('#upload-form').ajaxForm({
            success: function(msg) {
                alert("File has been uploaded successfully");
            },
            error: function(msg) {
                $("#upload-error").text("Couldn't upload file");
            }
        });
    });
</script>
<form id="upload-form" class="upload-box" action="upload" method="POST" enctype="multipart/form-data">
    <input type="file" id="file" name="file1" />
    <span id="upload-error" class="error">${uploadError}</span>
    <input type="submit" id="upload-button" value="upload" />
</form>
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);

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

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

     try {
         // Parse the request
         List items = upload.parseRequest(request);
         Iterator iterator = items.iterator();
         while (iterator.hasNext()) {
             FileItem item = (FileItem) iterator.next();
             if (!item.isFormField()) {
                 String fileName = item.getName();
                 String root = getServletContext().getRealPath("/");
                 File path = new File(root + "../../web/Images/uploads");
                 if (!path.exists()) {
                     boolean status = path.mkdirs();
                 }

                 File uploadedFile = new File(path + "/" + fileName);
                 System.out.println(uploadedFile.getAbsolutePath());
                 item.write(uploadedFile);
             }
         }
     } catch (FileUploadException e) {
         e.printStackTrace();
     } catch (Exception e) {
         e.printStackTrace();
     }
 }
Finicking answered 23/12, 2016 at 9:51 Comment(1)
Thank you for an example of server-side Java code to read what is posted. Most posts only show the Javascript, but handling in Java is different than most.Alderete

© 2022 - 2024 — McMap. All rights reserved.