0

I need to upload files that were added via drag and drop, and to do this I need to use jQUery and Ajax. I have a form where the user can select files via a Browse button, but the user should be able to add files via drag and drop. I do not want to use a plugin.

The Javascript for the drag and drop works, but I don't know how to actually upload the file now (something with FileReader?). Here is the function (with validation code removed) that gets the dropped file.

function handleFileSelect(e) {
    e.stopPropagation();
    e.preventDefault();

    var files = e.dataTransfer.files;

    for(var i = 0, f; f = files[i]; i++) {
        //i display the file name and do validation here
    }
}

I would like to be able to upload the files using jQuery's .ajax from here. Is this possible?

Lukas
  • 1,824
  • 2
  • 20
  • 21

2 Answers2

2

Here is a tutorial how to read the files client side:

Drag and Drop

Here is an example on how to upload the file.

html5-file-upload-jquery-php

Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100
Mark
  • 5,680
  • 2
  • 25
  • 26
1

Use FormData to upload files via ajax.

var data = new FormData();  
...
data.append('file', files[i]);    
...
$.ajax({..., data: data, contentType: false, processData: false, type: 'POST', ...});
Musa
  • 96,336
  • 17
  • 118
  • 137
  • Googled "jQuery Ajax FormData" and found this http://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax. The top answer on that question works for me! – Lukas Sep 15 '12 at 06:28