jQuery:File+Data upload using Blueimp File Upload plugin on form submit

后端 未结 2 526
栀梦
栀梦 2020-12-10 18:49

I am using Blueimp File Upload plugin to upload file. Let say I have following form:

相关标签:
2条回答
  • 2020-12-10 19:33

    Multi-file upload, with support for drag and drop and multibrowser support, is not possible without some tricks.

    With the jquery file upload plugin, you can set autoUpload to false, collect the files being added or dropped, and then on form submit, you cancel the normal submit request. Instead you do a single ajax call which will contain all your files and the form content. When the ajax call returns you can redirect back to your view page etc.

    var filesList = new Array();
    $(function () {
        $('#fileupload').fileupload({
            autoUpload: false,
         }).on('fileuploadadd', function (e, data) {
            $.each(data.files, function (index, file) {
                filesList.push(data.files[index]);
            });
        });
    }
    $("#uploadform").submit(function(event) {
        if (filesList.length > 0) {
            event.preventDefault();
            $('#fileupload').fileupload('send', {files: filesList})
                .complete(function (result, textStatus, jqXHR) { 
                    // window.location='back to view-page after submit?'
                });
            } else {
                // plain default submit
            }
        });
    });
    [...]
    <form id="uploadform" action="..." method="POST" enctype="multipart/form-data">
        <input type="text" name="dummy" placeholder="some other input field">
        <input id="fileupload" type="file" name="files" multiple="multiple">
    </form>
    

    I have described a fully working solution with a spring mvc controller in detail here

    0 讨论(0)
  • 2020-12-10 19:40

    You need something like this:

    var sendData= true;  
    $('#file').fileupload({
       dataType : 'json',
       autoUpload : false,
       add : function(e,data){
          $("#myForm button").on("click",function(){
              if(sendData){
                  data.formData = $("#myForm").serializeArray();              
                  sendData = false;
              }
    
              data.submit();
          });
       },
       done: function(e,data){
           sendData = true;
       }
    })
    

    here you can find more information about formData

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