Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // HTML part:
- // <input type="file" id="fileInput" />
- // <button onclick="uploadFile()">Upload</button>
- // <progress id="uploadProgress" value="0" max="100"></progress>
- async function uploadFile() {
- const fileInput = document.getElementById('fileInput');
- const file = fileInput.files[0];
- const progressElement = document.getElementById('uploadProgress');
- if (!file) {
- alert('Please select a file to upload.');
- return;
- }
- const formData = new FormData();
- formData.append('file', file);
- try {
- const xhr = new XMLHttpRequest();
- xhr.open('POST', 'https://your-server-endpoint/upload', true);
- xhr.upload.addEventListener('progress', (event) => {
- if (event.lengthComputable) {
- const percentComplete = (event.loaded / event.total) * 100;
- progressElement.value = percentComplete;
- }
- });
- xhr.onreadystatechange = () => {
- if (xhr.readyState === 4) {
- if (xhr.status === 200) {
- console.log('File uploaded successfully:', JSON.parse(xhr.responseText));
- } else {
- console.error('Error uploading file:', xhr.statusText);
- }
- }
- };
- xhr.send(formData);
- } catch (error) {
- console.error('Error uploading file:', error);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement