Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload operation of file asynchronously using jquery

I want to upload files asynchronously using jQuery. This is my HTML:

<input type="file" id="f" name="f"/>
<input id="upload" type="button" value="Upload"/>

And here my JavaScript code:

$(document).ready(function () {
$("#upload").click(function () {
    var filename = $("#f").val();

    $.ajax({
        type: "POST",
        url: "addFile.do",
        enctype: 'multipart/form-data',
        data: {
            file: filename
        },
        success: function () {
            alert("All Files Have Been Uploaded ");
        }
    });
});
});

I am getting file names only instead of actual file which I have uploaded

I am using theThis Plugin to upload files.

like image 939
Aditya Ekbote Avatar asked May 28 '14 07:05

Aditya Ekbote


1 Answers

Unlike you think, the code does NOT use that plugin to upload files. Instead you explicitly make an ajax request. The error occurs because the value of the <input type="file"> is the filename, and that is the only data you are sending in the request.

Instead you need to bind the form using $(form).ajaxform(); then in the click handler, you can trigger the submit event on the form.

Thus something like as follows ought to do the trick:

html:

<form method="post" action="addFile.do">
<input type="file" id="f" name="f"/>
<input id="upload" type="button" value="Upload"/>
</form>

And JavaScript:

$('form').ajaxform({
    success: function () {
        alert("All Files Have Been Uploaded ");
    }
});

$("#upload").click(function() {
    $('form').submit();
});
like image 161