How to Upload Files in JavaScript?

We upload files using JavaScript, for this we have to capture form elements, gather information from FormData for easier file uploads, intercept submission events, and utilize Fetch API for asynchronous server requests, for enhanced user experience and efficient data handling.

Approach

  • Project Setup: Create a directory then create HTML, CSS, and JavaScript files.
  • HTML Structure: Design the user interface with an HTML form including a file input element.
  • JavaScript Implementation: Write JavaScript to handle file selection events, prevent default form submission, and send file data to the server using Fetch or XMLHttpRequest.
  • Server-side Handling: Implement server-side code to receive and process file uploads, ensuring proper parsing, error handling, and security measures.

Example: This example shows the implementation of the above-explained approach.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form id="fileUploadForm">
        <input type="text" name="firstName" />
        File: <input type="file" name="upload" />
        <input type="submit" id="btn" />
     </form>
    <script src="script.js"> </script>
    
</body>
</html>
JavaScript
const form = document.getElementById("fileUploadForm");
const data = new FormData(form);
form.addEventListener("submit", async (event) => {
  event.preventDefault();

  let response = await fetch(
"https://jsonplaceholder.typicode.com/posts", {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-type": "application/json; charset=UTF-8",
      },
  });

  let result = await response.json();
  console.log(result);
});

Output:


Contact Us