jQuery file upload: Is it possible to trigger upload with a submit button?

前端 未结 8 2278
走了就别回头了
走了就别回头了 2020-12-01 01:40

I\'m using jQuery file upload for AJAX-based uploads. It always starts uploading after a file is selected. Is it possible to change the behavior to use the \"submit\"-button

相关标签:
8条回答
  • 2020-12-01 02:09

    if you have the button

    <button id="up_btn">Upload</button>
    

    You can try with

    $('#fileupload').fileupload({
        dataType: 'json',
        add: function (e, data) {            
            $("#up_btn").off('click').on('click', function () {
                data.submit();
            });
        },
    });
    

    EDIT: according to comments a better answer considere off to avoid duplicated requests. (also work unbind, I do not check if is bind and unbind but jquery team recommend on and off link since 1.7)

    0 讨论(0)
  • 2020-12-01 02:12

    None of these answers will work for multiple file uploads. My case involved allowing multiple attachments in a comment thread. So I needed to save the comment first to get the id, and then upload and save all the attachments. This seems like a trivial thing, but with this plugin its not that intuitive. My solution uses custom events in jQuery, and works great.

    The currently accepted answer binds to the click event of a button in the 'add' callback, but the 'add' callback is called once for each file. If you unbind all the events each time only the last file will upload.

    $('#fileupload').fileupload({
        dataType: 'json',
        add: function (e, data) {
            $("#up_btn").on('customName', function (e) {
                data.submit();
            });
        },
    });
    

    By binding the submit button to a custom name, we can do whatever preprocessing we want before submitting the images. In my case it involved submitting the comment and getting back the comment id which I did in a separate call. This code just responds to the click, but you can do whatever you want before triggering the event.

    $("#up_btn").on('click', function (e) {
        e.preventDefault();
        $("#up_btn").trigger( "customName");
    });
    

    You can pass any data you want when you trigger the event, so it really gives you complete control over your form.

    0 讨论(0)
提交回复
热议问题