javascript – How to get the name of the selected file in an input type = "file"?

Question:

I am trying to make some file type file on my website but I can't see what it is when a file is selected, I have tried to follow the example here: https://tympanus.net/codrops/2015/09/15/styling- customizing-file-inputs-smart-way /

.inputfile {
	width: 0.1px;
	height: 0.1px;
	opacity: 0;
	overflow: hidden;
	position: absolute;
	z-index: -1;
}
.fileUpload {
    position: relative;
    overflow: hidden;
    margin: 10px;
}
.fileUpload input.upload {
    position: absolute;
    top: 0;
    right: 0;
    margin: 0;
    padding: 0;
    font-size: 20px;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
}
<input id="image1" type="file" class="inputfile hidden-xs hidden-md" value="image1" name="image1" required />
<label for="image1" class="my-btn btn-danger"><center>Archivo 1</center></label><br>

What I want is that when I select a file instead of putting "File 1" put the name of the file and I don't know how to do it, I have tried to copy the js code that is in that web but when I put it it stops working at all .

Answer:

If what you want is simply the name of the file then you can get it directly from the input accessing the name attribute of the first file loaded in the input :

document.getElementById('image1').files[0].name;

However, if you try to get the path where this file is located, you can try this by doing this.value . However, as you can see, it returns a path that is not the real one of the file and replaces it with a fakepath . This is because for security reasons the path in which the user has stored the file is not added.

Your modified example:

document.getElementById('image1').onchange = function () {
  console.log(this.value);
  document.getElementById('fichero').innerHTML = document.getElementById('image1').files[0].name;
}
.inputfile {
	width: 0.1px;
	height: 0.1px;
	opacity: 0;
	overflow: hidden;
	position: absolute;
	z-index: -1;
}
.fileUpload {
    position: relative;
    overflow: hidden;
    margin: 10px;
}
.fileUpload input.upload {
    position: absolute;
    top: 0;
    right: 0;
    margin: 0;
    padding: 0;
    font-size: 20px;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
}
<input id="image1" type="file" class="inputfile hidden-xs hidden-md" value="image1" name="image1" required />
<label id="fichero" for="image1" class="my-btn btn-danger"><center>Archivo 1</center></label><br>
Scroll to Top