javascript upload file

javascript

To upload a file using JavaScript, you can use the HTML5 File API. Here’s an example code snippet:

HTML code:

<input type="file" id="myFileInput">
<button onclick="uploadFile()">Upload File</button>

JavaScript code:

function uploadFile() {
  const input = document.getElementById('myFileInput');
  const file = input.files[0];

  const formData = new FormData();
  formData.append('file', file);

  fetch('/upload', {
    method: 'POST',
    body: formData
  })
  .then(response => {
    console.log('File uploaded successfully');
  })
  .catch(error => {
    console.error('Error uploading file:', error);
  });
}

In the HTML code, we create an input element of type “file” and an HTML button that calls the uploadFile() function when clicked.

In the JavaScript code, we first get the selected file using the getElementById() method and accessing the files property of the input element.

Then, we create a new FormData object and append the file to it using the append() method.

Finally, we use the fetch() method to send a POST request to the server with the file data in the body of the request. In this example, we assume that the server will handle the file upload at the /upload endpoint. The response from the server is logged to the console.