@livechat/file-upload
Version:
Simple promisified XHR file upload with cancellation
83 lines (68 loc) • 2.02 kB
JavaScript
;
var toFormData = function toFormData(object) {
var formData = new FormData();
Object.keys(object).forEach(function (key) {
return formData.append(key, object[key]);
});
return formData;
};
var UPLOAD_FAILED = 'UPLOAD_FAILED';
var UPLOAD_CANCELED = 'UPLOAD_CANCELED';
var uploadFile = function uploadFile(url, data, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
headers = _ref.headers,
_ref$method = _ref.method,
method = _ref$method === void 0 ? 'POST' : _ref$method,
onProgress = _ref.onProgress,
_ref$withCredentials = _ref.withCredentials,
withCredentials = _ref$withCredentials === void 0 ? false : _ref$withCredentials;
var xhr = new XMLHttpRequest();
var upload = new Promise(function (resolve, reject) {
if (typeof onProgress === 'function') {
xhr.upload.onprogress = function (event) {
onProgress(event.loaded / event.total);
};
}
xhr.onload = function () {
var response;
try {
response = JSON.parse(xhr.response);
} catch (err) {
response = xhr.response;
}
if (xhr.status >= 200 && xhr.status < 300) {
resolve(response);
return;
}
var err = new Error('Upload failed.');
err.code = UPLOAD_FAILED;
err.response = response;
reject(err);
};
xhr.onerror = function () {
var err = new Error('Upload failed.');
err.code = UPLOAD_FAILED;
reject(err);
};
xhr.onabort = function () {
var err = new Error('Upload canceled.');
err.code = UPLOAD_CANCELED;
reject(err);
};
xhr.open(method, url);
xhr.withCredentials = withCredentials;
if (headers) {
Object.keys(headers).forEach(function (header) {
return xhr.setRequestHeader(header, headers[header]);
});
}
xhr.send(toFormData(data));
});
return {
promise: upload,
cancel: function cancel() {
xhr.abort();
}
};
};
module.exports = uploadFile;