We can upload the file by Web API.
Version
Brave 1.45.123
querySelector()
The file is uploaded by Web API.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HTML Lab</title>
</head>
<body>
<input type="file" id="uploadFile" onchange="onChange()" />
</body>
<script>
let onChange = () => {
let file = document.querySelector('#uploadFile').files[0]
console.log(file.name)
}
</script>
</html>
Line 9
<input type="file" id="uploadFile" onchange="onChange()" />
id
:defineid
to access the DOM element
Line 12
let onChange = () => {
let file = document.querySelector('#uploadFile').files[0]
console.log(file.name)
}
- Use
querySelector()
to access DOM element files
is Array. We can get the file from the first element of thefiles
Array
event
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HTML Lab</title>
</head>
<body>
<input type="file" onchange="onChange(event)" />
</body>
<script>
let onChange = ({ target: files }) => {
let file = files[0]
console.log(file.name)
}
</script>
</html>
Line 9
<input type="file" onchange="onChange(event)" />
- Use
event
to passevent
Object toonChange()
Line 12
let onChange = ({ target: files }) => {
let file = files[0]
console.log(file.name)
}
- Destructure
files
from parameter files
is Array. We can get the file from the first element of thefiles
Array
Conclusion
- We can use
event
to prevent usingquerySelector()
to access the DOM element