82 lines
2.3 KiB
TypeScript
82 lines
2.3 KiB
TypeScript
import axios, { type CancelTokenSource } from "axios";
|
|
import route from "./../../modules/route";
|
|
|
|
class CKUploadAdaptater {
|
|
route: string | null = "";
|
|
cancel: CancelTokenSource | null = null;
|
|
|
|
// @ts-ignore
|
|
constructor(loader) {
|
|
// The file loader instance to use during the upload.
|
|
// @ts-ignore
|
|
this.loader = loader;
|
|
this.cancel = axios.CancelToken.source();
|
|
}
|
|
|
|
// Starts the upload process.
|
|
upload() {
|
|
// @ts-ignore
|
|
return this.loader.file.then(
|
|
(file: File) =>
|
|
new Promise((resolve, reject) => {
|
|
this._initRequest();
|
|
this._sendRequest(file, resolve, reject);
|
|
})
|
|
);
|
|
}
|
|
|
|
// Aborts the upload process.
|
|
abort() {
|
|
if (this.cancel) {
|
|
this.cancel.cancel();
|
|
}
|
|
}
|
|
|
|
// Initializes the XMLHttpRequest object using the URL passed to the constructor.
|
|
_initRequest() {
|
|
this.route = route.methods.route("crud-policies.upload");
|
|
}
|
|
|
|
// Prepares the data and sends the request.
|
|
_sendRequest(
|
|
file: File,
|
|
resolve: (value: unknown) => void,
|
|
reject: (reason?: any) => void
|
|
) {
|
|
// Prepare the form data.
|
|
const data = new FormData();
|
|
data.append("upload", file);
|
|
const headers = Object.assign(
|
|
{},
|
|
window.axios ? window.axios.defaults.headers.common : {}
|
|
);
|
|
headers["Content-Type"] = "multipart/form-data";
|
|
|
|
if (!this.route) {
|
|
throw new Error("Route is not set");
|
|
}
|
|
|
|
axios
|
|
.post(this.route, data, {
|
|
withCredentials: true,
|
|
headers: headers,
|
|
onUploadProgress: (evt) => {
|
|
// @ts-ignore
|
|
this.loader.uploadTotal = evt.total;
|
|
// @ts-ignore
|
|
this.loader.uploaded = evt.loaded;
|
|
},
|
|
})
|
|
.then((response) => {
|
|
resolve({
|
|
default: response.data.url,
|
|
});
|
|
})
|
|
.catch((error) => {
|
|
console.error(error);
|
|
reject("Le fichier à été marbré");
|
|
});
|
|
}
|
|
}
|
|
|
|
export { CKUploadAdaptater };
|