Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add dropped file to a file input using jQuery

I have a custom file input:

<div id="wrapper">
    <span id="fake-text-input"></span>
    <button id="select-a-file"></button>
    <input id="hidden-file-input" type="file" />
</div>

The input[type="file"] is hidden (display: none) and selecting a file is handled by listening\triggering the click and change events.

I want to support file drop as well. I was able to listen to the drop event when a file is dropped on #fake-text-input but I don't know how to forward the drop event to the input[type="file"].. is it even possible?

I'm not interested in file input opacity tricks :)

$('body').on('drop', '#wrapper', function(e) {
    var file = e.originalEvent.dataTransfer.files[0];

    // I have the file.. now what?
});
like image 788
tamir Avatar asked Jan 10 '13 21:01

tamir


People also ask

How do I assign a file to an input type file?

The only way to set the value of a file input is by the user to select a file. This is done for security reasons. Otherwise you would be able to create a JavaScript that automatically uploads a specific file from the client's computer.


2 Answers

This is worked with me in google chrome , the problem now with other browsers

$("input[type='file']").prop("files", e.originalEvent.dataTransfer.files);
like image 86
NassimPHP Avatar answered Sep 21 '22 15:09

NassimPHP


From @NassimPHP 's answer, this worked!

$("input[type='file']").prop("files", e.dataTransfer.files);
like image 22
jerinisready Avatar answered Sep 20 '22 15:09

jerinisready