I am looking for a way to upload folders using Ajax Post. The post that I found (cp. File Entries from drop event) answered how to get the file entries but when I POST them, the server receives only the file names. Not the data. Now I am looking for a way to actually load the files. Since I am new to js I have no idea how to get forward.
The snipped that I found is this:
// Drop handler function to get all files
async function getAllFileEntries(dataTransferItemList) {
let fileEntries = [];
// Use BFS to traverse entire directory/file structure
let queue = [];
// Unfortunately dataTransferItemList is not iterable i.e. no forEach
for (let i = 0; i < dataTransferItemList.length; i++) {
queue.push(dataTransferItemList[i].webkitGetAsEntry());
}
while (queue.length > 0) {
let entry = queue.shift();
if (entry.isFile) {
fileEntries.push(entry);
} else if (entry.isDirectory) {
queue.push(...await readAllDirectoryEntries(entry.createReader()));
}
}
return fileEntries;
}
// Get all the entries (files or sub-directories) in a directory
// by calling readEntries until it returns empty array
async function readAllDirectoryEntries(directoryReader) {
let entries = [];
let readEntries = await readEntriesPromise(directoryReader);
while (readEntries.length > 0) {
entries.push(...readEntries);
readEntries = await readEntriesPromise(directoryReader);
}
return entries;
}
// Wrap readEntries in a promise to make working with readEntries easier
// readEntries will return only some of the entries in a directory
// e.g. Chrome returns at most 100 entries at a time
async function readEntriesPromise(directoryReader) {
try {
return await new Promise((resolve, reject) => {
directoryReader.readEntries(resolve, reject);
});
} catch (err) {
console.log(err);
}
}
My drop event looks like this:
elDrop.addEventListener('drop', async function (event) {
event.preventDefault();
let items = await getAllFileEntries(event.dataTransfer.items);
elItems.innerHTML = items.length;
$.ajax({
type: 'POST',
url: '{% url 'user:upload' %}',
dataType: "application/binary",
data: items,
success: function () {
alert('success')
}
});
});