7

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.

2

1 Answer 1

1

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();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.