[jquery] jQuery: get the file name selected from <input type="file" />

This code should work in IE (don't even test it in Firefox), but it doesn't. What I want is to display the name of the attached file. Any help?

<html>
<head>
  <title>example</title>    
  <script type="text/javascript" src="../js/jquery.js"></script>
  <script type="text/javascript">  
        $(document).ready( function(){            
      $("#attach").after("<input id='fakeAttach' type='button' value='attach a file' />");      
      $("#fakeAttach").click(function() {            
        $("#attach").click();        
        $("#maxSize").after("<div id='temporary'><span id='attachedFile'></span><input id='remove' type='button' value='remove' /></div>");        
        $('#attach').change(function(){
          $("#fakeAttach").attr("disabled","disabled");          
          $("#attachedFile").html($(this).val());
        });        
        $("#remove").click(function(e){
          e.preventDefault();
          $("#attach").replaceWith($("#attach").clone());
          $("#fakeAttach").attr("disabled","");
          $("#temporary").remove();
        });
      })
    }); 
  </script> 
</head>
<body>
  <input id="attach" type="file" /><span id="maxSize">(less than 1MB)</span>    
</body>
</html>

This question is related to jquery events copy file-io

The answer is


//get file input
var $el = $('input[type=file]');
//set the next siblings (the span) text to the input value 
$el.next().text( $el.val() );

Add a hidden reset button :

<input id="Reset1" type="reset" value="reset" class="hidden" />

Click the reset button to clear the input.

$("#Reset1").click();

<input onchange="readURL(this);"  type="file" name="userfile" />
<img src="" id="blah"/>
<script>
 function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah')
                    .attr('src', e.target.result)
                    .width(150).height(200);
        };

        reader.readAsDataURL(input.files[0]);
        //console.log(reader);
        //alert(reader.readAsDataURL(input.files[0]));
    }
}
</script>

The simplest way is to simply use the following line of jquery, using this you don't get the /fakepath nonsense, you straight up get the file that was uploaded:

$('input[type=file]')[0].files[0]; // This gets the file
$('#idOfFileUpload')[0].files[0]; // This gets the file with the specified id

Some other useful commands are:

To get the name of the file:

$('input[type=file]')[0].files[0].name; // This gets the file name

To get the type of the file:

If I were to upload a PNG, it would return image/png

$("#imgUpload")[0].files[0].type

To get the size (in bytes) of the file:

$("#imgUpload")[0].files[0].size

Also you don't have to use these commands on('change', you can get the values at any time, for instance you may have a file upload and when the user clicks upload, you simply use the commands I listed.


I had used following which worked correctly.

$('#fileAttached').attr('value', $('#attachment').val())

$('input[type=file]').change(function(e){
    $(this).parents('.parent-selector').find('.element-to-paste-filename').text(e.target.files[0].name);
});

This code will not show C:\fakepath\ before file name in Google Chrome in case of using .val().


It is just such simple as writing:

$('input[type=file]').val()

Anyway, I suggest using name or ID attribute to select your input. And with event, it should look like this:

$('input[type=file]').change(function(e){
  $in=$(this);
  $in.next().html($in.val());
});

<input onchange="readURL(this);"  type="file" name="userfile" />
<img src="" id="viewImage"/>
<script>
 function readURL(fileName) {
    if (fileName.files && fileName.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#viewImage')
                    .attr('src', e.target.result)
                    .width(150).height(200);
        };

        reader.readAsDataURL(fileName.files[0]);
    }
}
</script>

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to events

onKeyDown event not working on divs in React Detect click outside Angular component Angular 2 Hover event Global Events in Angular How to fire an event when v-model changes? Passing string parameter in JavaScript function Capture close event on Bootstrap Modal AngularJs event to call after content is loaded Remove All Event Listeners of Specific Type Jquery .on('scroll') not firing the event while scrolling

Examples related to copy

Copying files to a container with Docker Compose Copy filtered data to another sheet using VBA Copy output of a JavaScript variable to the clipboard Dockerfile copy keep subdirectory structure Using a batch to copy from network drive to C: or D: drive Copying HTML code in Google Chrome's inspect element What is the difference between `sorted(list)` vs `list.sort()`? How to export all data from table to an insertable sql format? scp copy directory to another server with private key auth How to properly -filter multiple strings in a PowerShell copy script

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js