Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Send The File Data Without Form With Ajax On Server?

I've coded a javascript code which nicely collects every file user wants to upload. But things turned when I added drag/drop file option. By default, I had a code which monitored input[type='file'] change event handler and once it was detected, actions were performed and files were sent to server for upload. But since drag/drop doesn't change the input[type='file'] value and neither I can change it programmatically due to security reasons, I'm struck how do I send files which are dragged and dropped on the site.

Here's some of my code:

document.getElementById('drop').addEventListener('drop', function (e) {
  e = e || window.event; 
  e.preventDefault();
  var dt    = e.dataTransfer;
  var files = dt.files;
  for (var i=0; i<files.length; i++) {
    var file = files[i];
    var reader = new FileReader();

    reader.readAsDataURL(file);
    addEventHandler(reader, 'loadend', function(e, file) {
    var bin           = this.result; 
    var filename       = file.name;
    var filesize  = (file.size/1048576).toFixed(2) + ' MB';
    alert(' '+filename+' '+filesize+' '); // DEBUGGING ONLY
    console.log("YEAY");
    if(filecheck(filename)) {       // Additional Function
    step2(filesize, filename, bin); // Additional Function
    $('.btn').click(function() {    // Button to be clicked to start upload
    $('#main_img_upload').submit(); // Form with that input[type='file']
    });
    }
    else {
    alert("Wrong File");
    return false;
    }
    }.bindToEventHandler(file), false);
  }
  return false;
});

Obviously, it starts upload but server doesn't receive anything as no change has been made to form. But I have all the necessary details (name of file, size of file, etc..)

Any help would be appreciated.

like image 679
mehulmpt Avatar asked Oct 31 '22 19:10

mehulmpt


1 Answers

Try out this code.

data.append("FileName", files[0]);

        $.ajax({
            url: "../",
            type: "POST",
            processData: false,
            contentType: false,
            data: data,
            success: function (data) {
                if (data) {

                }
            },
            error: function (er) {
                MSGBox(er);
            }

        });
    }
like image 86
aditya mukkawar Avatar answered Nov 09 '22 09:11

aditya mukkawar