Advertisement
umuro

Upload - JavaScript

Oct 12th, 2024
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // HTML part:
  2. // <input type="file" id="fileInput" />
  3. // <button onclick="uploadFile()">Upload</button>
  4. // <progress id="uploadProgress" value="0" max="100"></progress>
  5.  
  6. async function uploadFile() {
  7.   const fileInput = document.getElementById('fileInput');
  8.   const file = fileInput.files[0];
  9.   const progressElement = document.getElementById('uploadProgress');
  10.  
  11.   if (!file) {
  12.     alert('Please select a file to upload.');
  13.     return;
  14.   }
  15.  
  16.   const formData = new FormData();
  17.   formData.append('file', file);
  18.  
  19.   try {
  20.     const xhr = new XMLHttpRequest();
  21.     xhr.open('POST', 'https://your-server-endpoint/upload', true);
  22.  
  23.     xhr.upload.addEventListener('progress', (event) => {
  24.       if (event.lengthComputable) {
  25.         const percentComplete = (event.loaded / event.total) * 100;
  26.         progressElement.value = percentComplete;
  27.       }
  28.     });
  29.  
  30.     xhr.onreadystatechange = () => {
  31.       if (xhr.readyState === 4) {
  32.         if (xhr.status === 200) {
  33.           console.log('File uploaded successfully:', JSON.parse(xhr.responseText));
  34.         } else {
  35.           console.error('Error uploading file:', xhr.statusText);
  36.         }
  37.       }
  38.     };
  39.  
  40.     xhr.send(formData);
  41.   } catch (error) {
  42.     console.error('Error uploading file:', error);
  43.   }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement