js input file选择文件并显示出来
时间: 2023-09-01 19:01:41 浏览: 574
在JavaScript中,我们可以使用`<input type="file">`元素来实现文件选择功能。首先,在HTML中创建一个文件选择框:
```
<input type="file" id="fileInput">
```
然后,在JavaScript中获取文件选择框的元素,并为其添加一个`change`事件监听器:
```
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', handleFileSelect);
```
在`handleFileSelect`函数中,我们将获取选择的文件并显示出来:
```
function handleFileSelect(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
const fileContents = e.target.result;
console.log(file.name);
console.log(fileContents);
}
reader.readAsText(file);
}
```
在这个例子中,我们使用`FileReader`对象来读取文件内容。当文件加载完成后,`onload`回调函数将被调用,并可以通过`e.target.result`来获取文件内容。在这个例子中,我们将文件名和文件内容分别打印到控制台中。
如果你想将文件内容显示在页面上,可以创建一个用于显示文件内容的元素,并将文件内容赋给该元素的`innerText`属性:
```
function handleFileSelect(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
const fileContents = e.target.result;
const fileDisplay = document.getElementById('fileDisplay');
fileDisplay.innerText = fileContents;
}
reader.readAsText(file);
}
```
在这个例子中,我们假设在页面上存在一个`<div id="fileDisplay"></div>`元素来显示文件内容。通过将文件内容赋给`innerText`属性,文件内容将显示在该元素中。
这样,当用户选择一个文件后,选择的文件内容就会被读取并显示出来。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)