Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

blueimp

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

<form id="myForm">
   <input type="text" name="n1" />
   <input type="text" name="n3" />
   <input type="text" name="n3" />
   <input type="file" name="files" id="file" style="display: none" multiple/>
   <button>Upload</button>
</form>

My job is

I want to upload files+data when use click Upload button. I have done auto file upload i.e. uploading file just after drag drop or selecting file.

But for this one I have no idea how to do.Can I have some simple example for this kind of cases?

like image 444
Manish Kumar Avatar asked Jan 22 '14 11:01

Manish Kumar


Video Answer


2 Answers

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

like image 134
Dirty-flow Avatar answered Oct 23 '22 15:10

Dirty-flow


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

like image 5
Tor Avatar answered Oct 23 '22 15:10

Tor