files
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user