ivue-material-plus
Version:
A high quality UI components Library with Vue.js
65 lines (63 loc) • 1.67 kB
JavaScript
function getError(uploadUrl, option, xhr) {
const msg = `fail to post ${uploadUrl} ${xhr.status}`;
const error = new Error(msg);
error.status = xhr.status;
error.methods = "post";
error.url = uploadUrl;
return error;
}
function getBody(xhr) {
const text = xhr.responseText || xhr.response;
if (!text) {
return text;
}
try {
return JSON.parse(text);
} catch (e) {
return text;
}
}
function upload(option) {
if (typeof XMLHttpRequest === "undefined") {
return;
}
const xhr = new XMLHttpRequest();
const uploadUrl = option.uploadUrl;
if (xhr.upload) {
xhr.upload.onprogress = function progress(e) {
if (e.total > 0) {
e.percent = e.loaded / e.total * 100;
}
option.onProgress(e);
};
}
const formData = new FormData();
if (option.data) {
Object.keys(option.data).map((key) => {
formData.append(key, option.data[key]);
});
}
formData.append(option.filename, option.file);
xhr.onerror = function error(e) {
option.onError(e);
};
xhr.onload = function onload() {
if (xhr.status < 200 || xhr.status >= 300) {
return option.onError(getError(uploadUrl, option, xhr), getBody(xhr));
}
option.onSuccess(getBody(xhr));
};
xhr.open("post", uploadUrl, true);
if (option.withCredentials && "withCredentials" in xhr) {
xhr.withCredentials = true;
}
const headers = option.headers || {};
for (const item in headers) {
if (headers.hasOwnProperty(item) && headers[item] !== null) {
xhr.setRequestHeader(item, headers[item]);
}
}
xhr.send(formData);
}
export { upload as default };
//# sourceMappingURL=ajax.mjs.map