4

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");                               
}
});
ffffff01
  • 5,068
  • 11
  • 52
  • 61

3 Answers3

0

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>
john 4d5
  • 731
  • 6
  • 11
0

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.

ffffff01
  • 5,068
  • 11
  • 52
  • 61
  • @martin-g look at this question how to do it: http://stackoverflow.com/questions/13304838/how-to-upload-a-file-only-once-with-jquery-file-upload-plugin – Dirty-flow Nov 23 '12 at 09:20
  • I have found another better way to deal with ajax fileuploading. I am using jquery form plugin. It works just like a regular form and can handle file inputs. http://www.malsup.com/jquery/form/ – ffffff01 Nov 24 '12 at 14:10
0

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!

schmijos
  • 8,114
  • 3
  • 50
  • 58