@planjs/utils
Version:
🔧 Common tools collection
120 lines (93 loc) • 2.92 kB
JavaScript
function getError(option, xhr) {
var msg = "cannot ".concat(option.method, " ").concat(option.action, " ").concat(xhr.status, "'");
var err = new Error(msg);
err.status = xhr.status;
err.method = option.method;
err.url = option.action;
return err;
}
function getBody(xhr) {
var text = xhr.responseText || xhr.response;
if (!text) {
return text;
}
try {
return JSON.parse(text);
} catch (e) {
return text;
}
}
/**
* ä¸Šä¼ æ–‡ä»¶
* @param option
* @category Bom
*/
export default function upload(option) {
var xhr = new XMLHttpRequest();
if (option.onProgress && xhr.upload) {
xhr.upload.onprogress = function (e) {
var _e = e;
if (_e.total > 0) {
_e.percent = _e.loaded / _e.total * 100;
}
option.onProgress(_e);
};
}
var formData = new FormData();
if (option.data) {
Object.keys(option.data).forEach(function (key) {
var value = option.data[key];
if (Array.isArray(value)) {
value.forEach(function (item) {
formData.append("".concat(key, "[]"), item);
});
return;
}
formData.append(key, option.data[key]);
});
}
if (option.file instanceof Blob) {
formData.append(option.filename, option.file, option.file.name);
} else {
formData.append(option.filename, option.file);
}
xhr.onerror = function error(e) {
var _option$onError;
(_option$onError = option.onError) === null || _option$onError === void 0 ? void 0 : _option$onError.call(option, e);
};
xhr.onabort = function abort(e) {
var _option$onAbort;
(_option$onAbort = option.onAbort) === null || _option$onAbort === void 0 ? void 0 : _option$onAbort.call(option, e);
};
xhr.ontimeout = function timeout(e) {
var _option$onError2;
(_option$onError2 = option.onError) === null || _option$onError2 === void 0 ? void 0 : _option$onError2.call(option, e);
};
xhr.onload = function onload() {
var _option$onSuccess;
if ((xhr.status / 100 | 0) !== 2) {
var _option$onError3;
return (_option$onError3 = option.onError) === null || _option$onError3 === void 0 ? void 0 : _option$onError3.call(option, getError(option, xhr), getBody(xhr));
}
return (_option$onSuccess = option.onSuccess) === null || _option$onSuccess === void 0 ? void 0 : _option$onSuccess.call(option, getBody(xhr), xhr);
};
if (option.withCredentials && 'withCredentials' in xhr) {
xhr.withCredentials = true;
}
xhr.open(option.method, option.action, true);
var headers = option.headers || {};
if (headers['X-Requested-With'] !== null) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
Object.keys(headers).forEach(function (h) {
if (headers[h] !== null) {
xhr.setRequestHeader(h, headers[h]);
}
});
xhr.send(formData);
return {
abort: function abort() {
xhr.abort();
}
};
}