I am struggeling with the jquery file upload plugin is uploading my file as soon as I choose the file in my input field.

I want to have a cusom submit button that upload the file..

How can I do this?

Markup:

<span>Add File</span>
<input id="fileupload" type="file" multiple="" data-url="upload.ashx" name="files[]" />

<label for="file_name">Name:</label>
<input type="text" name="file_name" id="file_name" />

<input type="button" id="uploadFileBtn" value="Upload" />

Javascript:

$('#fileupload').fileupload(
{
dataType: 'json',
done: function (e, data) {
    alert("success");                               
}
});
有帮助吗?

解决方案 2

Solution

The fileupload has an ADD event that triggers as soon as a file is selected. I wrote my click event inside the ADD event and thereby overriding default behaviour.

Tested and it works as expected.

Solution 2 - Jquery Form Plugin

After some researching I found a better way to deal with ajax fileupload. I am using the Jquery Form Plugin found at: http://www.malsup.com/jquery/form/

It works just like a regular form and can handle file inputs.

其他提示

Are your inputs inside the same form?

Changing you code:

<form id="fileupload" action="someAction" method="POST" enctype="multipart/form-data">
    <span>Add files</span>
    <input type="file" name="files[]" multiple>
    <button type="submit" class="btn btn-primary start">
        <span>Start upload</span>
    </button>
</form>

You can do that by hooking into the add event. There you prevent the uploader from doing its default behavior. The jquery-file-upload-docs explain that, but it's a bit hard to find.

The following is written in the blueimp basic uploader tutorial:

$(function () {
    $('#fileupload').fileupload({
        dataType: 'json',
        add: function (e, data) {
            data.context = $('<button/>').text('Upload')
                .appendTo(document.body)
                .click(function () {
                    data.context = $('<p/>').text('Uploading...').replaceAll($(this));
                    data.submit();
                });
        },
        done: function (e, data) {
            data.context.text('Upload finished.');
        }
    });
});

It actually is very important, that the submit button you're creating is not inside the form!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top