102 lines
3.2 KiB
TypeScript
102 lines
3.2 KiB
TypeScript
import axios, { type CancelTokenSource } from "axios";
|
|
import type { Editor, FileLoader, FileRepository, UploadAdapter, UploadResponse } from "ckeditor5";
|
|
import route from "../modules/route";
|
|
|
|
interface UploadApiResponse {
|
|
url: string;
|
|
}
|
|
|
|
class CkUploadAdapter implements UploadAdapter {
|
|
private readonly loader: FileLoader;
|
|
private readonly folder: string;
|
|
private cancelTokenSource: CancelTokenSource | null = null;
|
|
private targetRoute: string = "";
|
|
|
|
constructor(loader: FileLoader, folder: string) {
|
|
// The file loader instance to use during the upload.
|
|
this.loader = loader;
|
|
this.folder = folder;
|
|
}
|
|
|
|
// Starts the upload process.
|
|
public upload(): Promise<UploadResponse> {
|
|
return this.loader.file.then((file: File | null) => {
|
|
if (!file) {
|
|
return Promise.reject(new Error("Aucun fichier valide fourni."));
|
|
}
|
|
|
|
return new Promise<UploadResponse>((resolve, reject) => {
|
|
this.initRequest();
|
|
this.sendRequest(file, resolve, reject);
|
|
});
|
|
});
|
|
}
|
|
|
|
// Aborts the upload process.
|
|
public abort(): void {
|
|
if (this.cancelTokenSource) {
|
|
this.cancelTokenSource.cancel("Upload annulé par l'utilisateur.");
|
|
this.cancelTokenSource = null;
|
|
}
|
|
}
|
|
|
|
// Initializes the request route and the cancellation token.
|
|
private initRequest(): void {
|
|
this.cancelTokenSource = axios.CancelToken.source();
|
|
this.targetRoute = route("bo.ckeditor.upload");
|
|
}
|
|
|
|
// Prepares the data and sends the request.
|
|
private sendRequest(
|
|
file: File,
|
|
resolve: (value: UploadResponse) => void,
|
|
reject: (reason?: unknown) => void
|
|
): void {
|
|
const data = new FormData();
|
|
data.append("upload", file);
|
|
data.append("folder", this.folder);
|
|
|
|
axios
|
|
.post<UploadApiResponse>(this.targetRoute, data, {
|
|
headers: {
|
|
"Content-Type": "multipart/form-data",
|
|
},
|
|
cancelToken: this.cancelTokenSource?.token,
|
|
onUploadProgress: (evt) => {
|
|
if (evt.total) {
|
|
this.loader.uploadTotal = evt.total;
|
|
}
|
|
this.loader.uploaded = evt.loaded;
|
|
},
|
|
})
|
|
.then((response) => {
|
|
resolve({
|
|
default: response.data.url,
|
|
});
|
|
})
|
|
.catch((error: unknown) => {
|
|
if (axios.isCancel(error)) {
|
|
console.warn("Upload annulé :", error.message);
|
|
return;
|
|
}
|
|
|
|
console.error(error);
|
|
reject("Le fichier a été marbré");
|
|
});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* CKEditor 5 upload plugin.
|
|
*/
|
|
function CkUploadAdapterPlugin(editor: Editor): void {
|
|
const fileRepository = editor.plugins.get("FileRepository") as FileRepository;
|
|
const folder = (editor.config.get("folder") as string) || "";
|
|
|
|
fileRepository.createUploadAdapter = (loader: FileLoader): UploadAdapter => {
|
|
return new CkUploadAdapter(loader, folder);
|
|
};
|
|
}
|
|
|
|
export default CkUploadAdapterPlugin;
|
|
export { CkUploadAdapter };
|