點燈坊

失くすものさえない今が強くなるチャンスよ

Uploading File by Alpine

Sam Xiao's Avatar 2022-11-10

We can upload the file by Alpine without Web API.

Version

Alpine 3.10

$el

upload000

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:fire onChange() on change event
  • $el:use $el to pass the current element to onChange()

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 the files Array

Conclusion

  • We can also use $refs to implement uploading file, but $el is more concise