This is the uploaded form.
Using Bootstrap
Remove form-control-file Class from input field to avoid unwanted horizontal scroll bar
Try this!!
$('#upload').change(function() {
var filename = $('#upload').val();
if (filename.substring(3,11) == 'fakepath') {
filename = filename.substring(12);
} // For Remove fakepath
$("label[for='file_name'] b").html(filename);
$("label[for='file_default']").text('Selected File: ');
if (filename == "") {
$("label[for='file_default']").text('No File Choosen');
}
});
.custom_file {
margin: auto;
opacity: 0;
position: absolute;
z-index: -1;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="upload" class="btn btn-sm btn-primary">Upload Image</label>
<input type="file" class="text-center form-control-file custom_file" id="upload" name="user_image">
<label for="file_default">No File Choosen </label>
<label for="file_name"><b></b></label>
</div>
Try this to Get filename from input [type='file'] using jQuery.
<script type="text/javascript">
$(document).ready(function(){
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
alert('The file "' + fileName + '" has been selected.');
});
});
</script>
Taken from @ jQueryPot
This isn't possible due to security reasons. At least not on modern browsers. This is because any code getting access to the path of the file can be considered dangerous and a security risk. Either you'll end up with an undefined value, an empty string or an error will be thrown.
When a file form is submitted, the browser buffers the file temporarily into an upload directory and only the temporary file name of that file and basename of that file is submitted.
var file = $('#YOURID > input[type="file"]');
file.value; // filename will be,
In Chrome, it will be something like C:\fakepath\FILE_NAME
or undefined
if no file was selected.
It is a limitation or intention that the browser does not reveal the file structure of the local machine.
There is no jQuery function for this. You have to access the DOM element and check the files property.
document.getElementById("image_file").files[0];
Or
$('#image_file')[0].files[0]
You have to do this on the change event of the input type file
this way:
$('#select_file').click(function() {
$('#image_file').show();
$('.btn').prop('disabled', false);
$('#image_file').change(function() {
var filename = $('#image_file').val();
$('#select_file').html(filename);
});
});