directory
directory

Reputation: 3167

How to get value of dropped file in file input using jquery?

Is it possible to set the data of a dropped file in a file upload input field? Or need a dropped file to be uploaded instantly to the server?

Example code:

<input type="file" id="drop-box" />
$("#drop-box").on('drop', function (e) {
    e.stopPropagation();
    e.preventDefault();      
    var files = e.originalEvent.dataTransfer.files;
    readURL(files);
});

Upvotes: 2

Views: 2016

Answers (1)

Mohammad
Mohammad

Reputation: 21499

You can use $('input')[0].files[0] instead e.originalEvent.dataTransfer.files.

The drop event is fired when an element or text selection is dropped on a valid drop target.

When you drop file into input, JQuery drop event fired, while it doesn't select file. You need to wait few time that file does select.

Run bottom example and drop file on input to see result.

$("#drop-box").on('drop', function (e){
    setTimeout(function(){   
        e.stopPropagation(); 
        var files = $('#drop-box')[0].files[0];
        
        $("p").text(files.name);
        $('#drop-box').val("");
    },1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="drop-box" />
<p></p>

Upvotes: 1

Related Questions