0

HTML

<div style="width:200px">
<form action="javascript:_bulkUser();" method="post" enctype="multipart/form-data">  
    Select File:<input type="file" name="fname"/><br/>  
    <input type="submit" value="upload"/>  
</form>

</div>

js(ajax call)

_bulkUser : function(scope) {
    try {
        $.ajax({
            type : "post",
            url : "FileUploadServlet",
            success : function(data) {
                alert('Sucess');
            },
            error : function(data) {
                console.log(data);
            }
        });
    } catch (e) {
        console.log(e);
    }
}

Servlet

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

    response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 
    System.out.println("working");
    MultipartRequest mp = new MultipartRequest(request, "e:/new");
    out.print("successfully uploaded"); 
}
mnille
  • 1,328
  • 4
  • 16
  • 20
Nitish Ks
  • 1
  • 1
  • 1
  • 1

2 Answers2

-1

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 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 jQuery Form plugin (example here).

Assuming that your JSP with the HTML form is rewritten in such way so that it's not broken when the client has JS 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 help of 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 to upload files to server using JSP/Servlet?

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

if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
    // Return ajax response (e.g. write JSON or XML).
} else {
    // Return 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 File Upload to Java Servlet and sending a file as multipart through xmlHttpRequest.

Community
  • 1
  • 1
jarvo69
  • 7,908
  • 2
  • 18
  • 28
  • A fat downvote for shameless [plagiarism](http://meta.stackexchange.com/questions/160077/users-are-calling-me-a-plagiarist-what-do-i-do). Go stand in the corner. – BalusC Aug 02 '16 at 07:48
-1

This code also works fine for me :

$('#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>
jarvo69
  • 7,908
  • 2
  • 18
  • 28
  • throwing exception when i runs my codes which i postedSEVERE: Servlet.service() for servlet [com.apptium.eportal.servlet.FileUploadServlet] in context with path [/eportal] threw exception java.io.IOException: Posted content type isn't multipart/form-data – Nitish Ks Aug 02 '16 at 10:08