我有一个包含文件上传输入的表单
<form action="abc.php" method="post">
<input name="fileToUpload" type="file" />
<div id="view"></div>
<button type="submit" value="submit" name="submit">Submit</button>
</form>
我希望获取单击此输入时上传的文件/图像的名称,并将其显示在<div id="view"></div>
下,但这需要在表单提交之前完成。任何人都可以告诉我们如何做到这一点
答案 0 :(得分:1)
尝试将代码更新为以下内容,
<form action="abc.php" method="post">
<input name="fileToUpload" id="files" type="file" />
<div id="view"></div>
<button type="submit" value="submit" name="submit">Submit</button>
</form>
<script>
var control = document.getElementById("files");
control.addEventListener("change", function(event) {
// When the control has changed, there are new files
var i = 0,
files = control.files,
len = files.length;
for (; i < len; i++) {
document.getElementById('view').innerHTML = files[i].name;
}
}, false);
</script>
我希望这会有所帮助。
答案 1 :(得分:0)
试试这段代码,一定会有所帮助
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
脚本代码
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);