用纯JS语言实现文件读写的功能的html
时间: 2024-05-04 12:21:24 浏览: 8
实现文件读写功能需要使用浏览器提供的 File API,以下是一个简单的 HTML 文件,可以实现文件的读取和写入功能:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件读写</title>
</head>
<body>
<input type="file" id="file-input">
<button id="read-btn">读取文件</button>
<br>
<textarea id="content" rows="10" cols="50"></textarea>
<br>
<button id="write-btn">写入文件</button>
<script>
// 获取DOM元素
const fileInput = document.getElementById('file-input')
const readBtn = document.getElementById('read-btn')
const writeBtn = document.getElementById('write-btn')
const content = document.getElementById('content')
// 读取文件
readBtn.addEventListener('click', () => {
const file = fileInput.files[0]
const reader = new FileReader()
reader.readAsText(file, 'utf-8')
reader.onload = () => {
content.value = reader.result
}
})
// 写入文件
writeBtn.addEventListener('click', () => {
const text = content.value
const blob = new Blob([text], { type: 'text/plain;charset=utf-8' })
const fileName = 'example.txt'
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
})
</script>
</body>
</html>
```
代码解释:
1. 使用`<input type="file">`元素来实现文件选择功能;
2. 使用`FileReader`对象读取文件内容,并将读取结果显示在`<textarea>`元素中;
3. 使用`Blob`对象创建文件并下载。