Reputation: 182
I'm trying to get the file through input
.
I hide the input through CSS and gave the label a style. There is a problem here.
If input is hidden, the default input button cannot support the supported get file name. I guess Vanila JS can solve this, but I don't know what to do. I tried to get the value value of the file and put it in the box specified as inner HTML, but it didn't work.
.submit{
width:140px;
height:40px;
background-color:red;
color:#fff;
text-align:center;
padding:10px;
line-height:40px;
cursor:pointer;
}
<input type="file" id="test" style="display:none;">
<label for="test">
<span class="submit">submit</span>
<span id="test2">filename</span>
</label>
Upvotes: 0
Views: 1115
Reputation: 59
Your HTML
<input type="file" id="test" style="display:none;">
<label for="test">
<span class="submit">submit</span>
<span id="test2">filename</span>
</label>
Your CSS
.submit{
width:140px;
height:40px;
background-color:red;
color:#fff;
text-align:center;
padding:10px;
line-height:40px;
cursor:pointer;
}
And Javascript
let file = document.querySelector('#test');
let test2 = document.querySelector('#test2');
file.addEventListener('change', function(e){
test2.innerHTML = e.target.files[0].name;
});
Demo here https://jsfiddle.net/jozsefk/4gwzrj38/
Upvotes: 0
Reputation: 5084
Following this Answer, you can get the file name, and use innerHTML
to show it to user.
document.getElementById('test').addEventListener("change", function() {
var fullPath = document.getElementById('test').value;
if (fullPath) {
var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
var filename = fullPath.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
document.getElementById("test2").innerHTML = filename;;
}
});
.submit {
width: 140px;
height: 40px;
background-color: red;
color: #fff;
text-align: center;
padding: 10px;
line-height: 40px;
cursor: pointer;
}
<input type="file" id="test" style="display:none;">
<label for="test">
<span class="submit">submit</span>
<span id="test2">filename</span>
</label>
Upvotes: 1