我有以下JS / HTML代码:
<input type="text" class="file" name="file_info" id="file_info">
<div class="file_upload">
<input type="file" id="file_upload" onchange="name();">
</div>
<script>
function name() {
var fileName = document.getElementById("file_upload").value;
var fnSplit = fileName.split(/[\/\\]/);
fileName = fnSplit[fnSplit.length - 1];
document.getElementById('file_info').innerHTML = 'Fred Flinstone';
}
</script>
我希望在上传文件后,文件名将显示在tput文本中,但此文件不起作用。
我该如何解决?
更新:文件名应位于输入文本
内答案 0 :(得分:2)
答案 1 :(得分:0)
您可以尝试以下代码:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var fileName =document.getElementById("file_upload").value;
var fnSplit = fileName.split(/[\/\\]/);
fileName = fnSplit[fnSplit.length - 1];
document.getElementById('file_info').value = fileName
}
</script>
</head>
<body>
<input type="text" class="file" name="file_info" id="file_info">
<div class="file_upload">
<input type="file" id="file_upload" onchange="myFunction();">
</div>
</body>
</html>
答案 2 :(得分:-2)
这样做:
<div class="file_upload">
<input type="file" id="file_upload">
</div>
<div id="file_info"></div>
function name(file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function (event) {
document.getElementById('file_info').innerHTML = "Filename: " + file.name + "\nContent: " + event.target.result;
};
reader.onerror = function () {
alert('Unable to read ' + file.name);
};
}
document.getElementById('file_upload').onchange = function () {
name(this.files[0]);
};