Skip to content
JavaScript

Datei-Upload

Datei-Upload mit Fortschritt und Chunking-Unterstützung wrappen.

#file#upload#FormData

Code

javascript
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);
  });
}