Files
lucent-laravel/front/js/modules/upload.js
T
2026-01-13 17:51:19 +02:00

59 lines
1.7 KiB
JavaScript

import { getApp } from "../app";
export function uploadFile(file, recordId, fieldId, locale, progress, error) {
const app = getApp();
const csrf = document.querySelector('meta[name="csrf-token"]').content;
const chunkSize = 2 * 1024 * 1024; // 2MB
const totalChunks = Math.ceil(file.size / chunkSize);
// Start the recursive process
sendChunk(0, null);
function sendChunk(currentChunk, fileId) {
const start = currentChunk * chunkSize;
const end = Math.min(start + chunkSize, file.size);
const chunk = file.slice(start, end);
const formData = new FormData();
formData.append("file", chunk);
if (fileId) {
formData.append("fileId", fileId);
}
formData.append("recordId", recordId);
formData.append("fieldId", fieldId);
formData.append("isLast", currentChunk === totalChunks - 1);
formData.append("filename", file.name);
formData.append("locale", locale);
formData.append("_token", csrf);
const xhr = new XMLHttpRequest();
xhr.open("POST", app.url("upload"), true);
// Success Callback
xhr.onload = function () {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
let fileId = response.fileId;
const nextChunk = currentChunk + 1;
if (nextChunk < totalChunks) {
progress({
pct: Math.round((nextChunk / totalChunks) * 100),
isComplete: false,
});
sendChunk(nextChunk, fileId);
} else {
progress({
pct: 100,
isComplete: true,
});
}
} else {
error("Upload failed at chunk " + currentChunk);
}
};
xhr.send(formData);
}
}