點燈坊

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

Uploading Files by Web API

Sam Xiao's Avatar 2022-11-10

We can upload the file by Web API.

Version

Brave 1.45.123

querySelector()

upload000

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:define id 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 the files 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 pass event Object to onChange()

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

Conclusion

  • We can use event to prevent using querySelector() to access the DOM element