"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to send a file to a server and monitor its upload progress using JavaScript?

How to send a file to a server and monitor its upload progress using JavaScript?

Published on 2024-11-12
Browse:946

How to send a file to a server and monitor its upload progress using JavaScript?

Sending Files in JavaScript

Suppose you have an HTML element representing a button that lets users select a file. Upon clicking the button and choosing a file, its name is stored in document.getElementById("image-file").value. If the server supports multi-part POST requests at the URL "/upload/image," how do you send the file to that endpoint? Additionally, how do you monitor the upload's progress?

Pure JavaScript with Fetch

You can use the fetch API with optional await-try-catch handling:

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();

formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});

Example with Async-Try-Catch

This example also includes user data sent as JSON:

async function SavePhoto(inp) {
  let user = { name: 'john', age: 34 };
  let formData = new FormData();
  let photo = inp.files[0];

  formData.append("photo", photo);
  formData.append("user", JSON.stringify(user));

  const ctrl = new AbortController(); // for timeout
  setTimeout(() => ctrl.abort(), 5000);

  try {
    let r = await fetch('/upload/image', {
      method: "POST",
      body: formData,
      signal: ctrl.signal,
    });
    console.log('HTTP response code:', r.status);
  } catch (e) {
    console.log('Huston we have problem...:', e);
  }
}

Monitoring Upload Progress

Unfortunately, methods like request.onprogress are not supported in HTML5 file upload with fetch, but you can monitor the overall upload progress by listening to network events:

let xhr = new XMLHttpRequest();

xhr.upload.addEventListener('progress', function(e) {
  if (e.lengthComputable) {
    let percentComplete = (e.loaded / e.total) * 100;
    console.log('Upload progress:', percentComplete   '%');
  }
});

xhr.open('POST', '/upload/image');
xhr.send(formData);
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3