3

Is there any way to be able to detect with jQuery, when a file is uploaded to an input element like below:

<input type='file' name='filex' id='filex' style="height: 2.3em" size="23" />

I'm looking for an event specific to when the file is placed (uploaded) to the element, not when the element is clicked before the open file dialog is opened. I'm aware that I can submit the form and then get the file server side, but I want to display a thumbnail to the user before the form is submitted on confirm.

Thanks.

Mohammad Sepahvand
  • 17,364
  • 22
  • 81
  • 122
  • 1
    I think you're misusing the word `uploaded`. To me that means the file's data has been fully transmitted to the server. I think you're going for when a file path is selected. – armen.shimoon Dec 02 '12 at 11:45
  • 2
    Why not use `change()`? Since the input will start 'empty' (and a file can't be programatically added, without user-interaction) any addition of a file will necessarily invoke the `change` event. – David Thomas Dec 02 '12 at 11:46
  • cool, any better word to describe the scenario? – Mohammad Sepahvand Dec 02 '12 at 11:46

2 Answers2

3

As a file input will start off with no files selected, and no files can be selected without user-interaction, I'd suggest using the change() method (using the change event):

$('input:file').change(
    function(e){
        console.log('file "' + path.split('\\').pop(); + '" selected.');
    });

References:

Community
  • 1
  • 1
David Thomas
  • 249,100
  • 51
  • 377
  • 410
1
var fileInput = document.getElementById('filex');

fileInput.onchange = function(e){
    if(e.target.files.length > 0)
        // File uploaded
}
karaxuna
  • 26,752
  • 13
  • 82
  • 117