Lukas
Lukas

Reputation: 1864

Drag and Drop jQuery Ajax Upload

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?

Upvotes: 0

Views: 6005

Answers (2)

Mark
Mark

Reputation: 5720

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

Upvotes: 2

Musa
Musa

Reputation: 97672

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', ...});

Upvotes: 1

Related Questions