emachine
emachine

Reputation: 1163

Send drag and drop file to input type file element

I have a form builder and I want to add drag and drop file capabilities.

Where I'm stuck is that all the resources I'm coming across upload the image via xhr when dropped. I want the image to persist until the form is submitted.

Ideally the event.dataTransfer.files[0] object would be transferred to the <input type="file" ...value="[dropped-file]"> element.

Currently I'm unable to make this happen. Do they use compatible data types?

Upvotes: 4

Views: 2337

Answers (1)

nicksweet
nicksweet

Reputation: 3999

You could just create and send a form after your drop event has occurred, and the user clicks a conf button. Heres the gist of it: (not tested).

function uploadFile(file) {
    var form = new FormData(),
        xhr = new XMLHttpRequest();

    form.append('media', file);
    xhr.open('POST', '/myurl/');

    xhr.onprogress = function(e) {
        showProgress();
    }

    xhr.onload = function(e) {
        showSuccessConf();
    }

    xhr.send(form);
}

uploadFile(event.dataTransfer.files[0]);

Upvotes: 3

Related Questions