Skip to content
JavaScript

File Upload

Wrap file upload with progress and chunking support.

By EZ4Code Team
fileuploadFormData

Code

function upload(url, file, onProgress) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.upload.onprogress = e => {
      if (e.lengthComputable) onProgress?.(e.loaded / e.total);
    };
    xhr.onload = () => xhr.status === 200 ? resolve(JSON.parse(xhr.responseText)) : reject(xhr);
    xhr.onerror = () => reject(xhr);
    const fd = new FormData();
    fd.append("file", file);
    xhr.open("POST", url);
    xhr.send(fd);
  });
}

Explanation

Implements file upload with progress callback via XMLHttpRequest.

More JavaScript Snippets