We can upload the file by Alpine without Web API.
Version
Alpine 3.10
$el
The file is uploaded by Alpine.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<title>Alpine Lab</title>
</head>
<body x-data>
<input type="file" @change="onChange($el)" />
</body>
<script>
let onChange = ({ files }) => {
let file = files[0]
console.log(file.name)
}
</script>
</html>
Line 9
<body x-data>
<input type="file" @change="onChange($el)" />
</body>
x-data
:define Alpine component@change
:fireonChange()
onchange
event$el
:use$el
to pass the current element toonChange()
Line 13
let onChange = ({ 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 also use
$refs
to implement uploading file, but$el
is more concise