mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-04 11:07:35 +01:00
filer UI, admin: upload a folder (#12371)
* admin: place uploaded files by their path inside an uploaded folder The multipart file name keeps only the base name, so the upload API takes an optional relativePaths field listing each file's path under the target directory. Paths that are empty, absolute or contain . or .. components are rejected per file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: upload a folder from the file browser The upload modal gets a folder picker, and a folder dropped on the listing is walked into, so its files upload with their subfolder paths. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer UI: upload a folder An Upload Folder button picks a whole folder, and a folder dropped on the listing is walked into. Each file is posted to its subfolder under the current directory, which the filer creates on the first upload into it. Progress rows are keyed by that path, so equal names in different subfolders no longer share a row. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: reject an empty relativePaths field instead of ignoring it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: upload a large selection in batches below the multipart part limit Go's multipart parser rejects a form of more than 1000 parts, so a folder of about a thousand files failed as a whole. The upload modal now sends 500 files per request and sums the results; progress covers all batches, and the button stays disabled until the last one finishes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: escape file names in upload error messages A failed upload reports the client-supplied file or folder path, and the toast renders its message as HTML. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: list failed uploads in the modal and reload the listing when it closes A partial upload logged its failures only to the console before the page reloaded, and a batch that failed after earlier ones succeeded left the listing stale. The failures now stay in the open modal, and closing it reloads the listing once any file was uploaded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: cancel the upload when its modal closes Closing the modal, including with its Cancel button, left the batch loop running, so the remaining batches were still written. The batch in flight is now aborted, which also stops the loop, and the listing reloads since the aborted request may already have stored files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: count upload progress by files when the selection has no bytes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: keep the newest upload selection when a folder drop finishes late Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: cap the upload preview at a fixed number of rows A folder of many thousands of files rendered one preview row per file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer UI: upload a few files at a time Every selected file started its own request at once, so a large folder opened thousands of requests together. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: regenerate the gzipped admin.js Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: reload the listing after a batch fails without a result A batch that fails mid-request may still have stored some of its files, so closing the modal reloads the listing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: stop reading a folder drop once a newer selection replaces it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: skip the read error of a folder drop a newer selection replaced Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer UI: share the four-upload limit across selections Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: regenerate the gzipped admin.js Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: set up the file browser handlers once admin.js already runs setupFileManagerEventHandlers on DOMContentLoaded, so the file browser page registered every listener twice and each drop was read twice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d5e359d0e2
commit
2ec0623073
7 files changed
+414
-155
No files matched your search
@@ -4,6 +4,7 @@ import (
|
||||
"bufio"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -289,13 +290,26 @@ func (h *FileBrowserHandlers) UploadFile(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// A folder upload names each file by its path inside the folder; the multipart
|
||||
// file name keeps only the base name.
|
||||
var relativePaths []string
|
||||
if v, ok := r.MultipartForm.Value["relativePaths"]; ok {
|
||||
if len(v) != 1 || json.Unmarshal([]byte(v[0]), &relativePaths) != nil || len(relativePaths) != len(files) {
|
||||
writeJSONError(w, http.StatusBadRequest, "relativePaths must list one path per uploaded file")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var uploadResults []map[string]interface{}
|
||||
var failedUploads []string
|
||||
|
||||
// Process each uploaded file
|
||||
for _, fileHeader := range files {
|
||||
for i, fileHeader := range files {
|
||||
// Validate file name
|
||||
fileName := fileHeader.Filename
|
||||
if relativePaths != nil {
|
||||
fileName = relativePaths[i]
|
||||
}
|
||||
if fileName == "" {
|
||||
failedUploads = append(failedUploads, "invalid filename")
|
||||
continue
|
||||
@@ -303,6 +317,10 @@ func (h *FileBrowserHandlers) UploadFile(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
// Normalize Windows-style backslashes to forward slashes
|
||||
fileName = util.CleanWindowsPath(fileName)
|
||||
if relativePaths != nil && !isRelativeUploadPath(fileName) {
|
||||
failedUploads = append(failedUploads, fmt.Sprintf("%s: invalid relative path", fileName))
|
||||
continue
|
||||
}
|
||||
|
||||
// Create full path for the file using path.Join for URL path semantics
|
||||
// path.Join handles double slashes and is not OS-specific like filepath.Join
|
||||
@@ -349,6 +367,16 @@ func (h *FileBrowserHandlers) UploadFile(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// isRelativeUploadPath reports whether name stays inside the upload directory.
|
||||
func isRelativeUploadPath(name string) bool {
|
||||
for _, part := range strings.Split(name, "/") {
|
||||
if part == "" || part == "." || part == ".." {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// uploadFormOverhead allows for the multipart headers and the path field on
|
||||
// top of the file bytes an upload may carry. Go's multipart parser accepts at
|
||||
// most 1000 parts, whose headers take about half of this.
|
||||
|
||||
@@ -216,3 +216,58 @@ func TestUploadFile_RemovesSpooledParts(t *testing.T) {
|
||||
t.Errorf("spooled parts left behind: %v", left)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsRelativeUploadPath(t *testing.T) {
|
||||
for name, want := range map[string]bool{
|
||||
"a.txt": true,
|
||||
"photos/a.jpg": true,
|
||||
"a/b/c/..x.txt": true,
|
||||
"/etc/a": false,
|
||||
"a/../../b": false,
|
||||
"..": false,
|
||||
"a//b": false,
|
||||
"./a": false,
|
||||
"a/": false,
|
||||
} {
|
||||
if got := isRelativeUploadPath(name); got != want {
|
||||
t.Errorf("isRelativeUploadPath(%q) = %v, want %v", name, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadFile_FolderRelativePaths(t *testing.T) {
|
||||
h := &FileBrowserHandlers{adminServer: &dash.AdminServer{}}
|
||||
upload := func(relativePaths string) *httptest.ResponseRecorder {
|
||||
var body bytes.Buffer
|
||||
mw := multipart.NewWriter(&body)
|
||||
for _, name := range []string{"a.txt", "b.txt"} {
|
||||
part, err := mw.CreateFormFile("files", name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
part.Write([]byte(name))
|
||||
}
|
||||
mw.WriteField("path", "/buckets/b")
|
||||
mw.WriteField("relativePaths", relativePaths)
|
||||
mw.Close()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/files/upload", &body)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
w := httptest.NewRecorder()
|
||||
h.UploadFile(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
for _, paths := range []string{`["dir/a.txt"]`, `not json`, ``, `null`} {
|
||||
if w := upload(paths); w.Code != http.StatusBadRequest {
|
||||
t.Errorf("relativePaths %s: expected 400, got %d (body: %s)", paths, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
w := upload(`["../a.txt", "dir\\..\\..\\b.txt"]`)
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("expected every escaping path to fail, got %d (body: %s)", w.Code, w.Body.String())
|
||||
}
|
||||
if strings.Count(w.Body.String(), "invalid relative path") != 2 {
|
||||
t.Errorf("expected both paths rejected before upload, got %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
+222
-129
@@ -1167,18 +1167,132 @@ async function submitCreateFolder() {
|
||||
}
|
||||
}
|
||||
|
||||
// Files dropped on the listing, each with its path under the current directory;
|
||||
// null when the modal's inputs hold the selection.
|
||||
let droppedUploadFiles = null;
|
||||
// Bumped by every drop and picker change, so a slow folder read cannot replace a newer selection.
|
||||
let uploadSelection = 0;
|
||||
|
||||
function selectedUploadFiles() {
|
||||
if (droppedUploadFiles) {
|
||||
return droppedUploadFiles;
|
||||
}
|
||||
const selected = [];
|
||||
['fileInput', 'folderInput'].forEach(id => {
|
||||
const input = document.getElementById(id);
|
||||
Array.from((input && input.files) || []).forEach(file => {
|
||||
selected.push({ file, path: file.webkitRelativePath || file.name });
|
||||
});
|
||||
});
|
||||
return selected;
|
||||
}
|
||||
|
||||
// Lists the dropped files, walking into dropped folders and stopping once
|
||||
// isCurrent turns false. The entries must be taken before the first await,
|
||||
// while the drop event still exposes them.
|
||||
async function collectDroppedFiles(dataTransfer, isCurrent) {
|
||||
const entries = Array.from(dataTransfer.items || [])
|
||||
.map(item => item.webkitGetAsEntry && item.webkitGetAsEntry())
|
||||
.filter(Boolean);
|
||||
if (entries.length === 0) {
|
||||
return Array.from(dataTransfer.files).map(file => ({ file, path: file.name }));
|
||||
}
|
||||
const collected = [];
|
||||
async function walk(entry) {
|
||||
if (!isCurrent()) {
|
||||
return;
|
||||
}
|
||||
if (entry.isFile) {
|
||||
const file = await new Promise((resolve, reject) => entry.file(resolve, reject));
|
||||
collected.push({ file, path: entry.fullPath.replace(/^\/+/, '') });
|
||||
return;
|
||||
}
|
||||
const reader = entry.createReader();
|
||||
while (isCurrent()) {
|
||||
const batch = await new Promise((resolve, reject) => reader.readEntries(resolve, reject));
|
||||
if (batch.length === 0) {
|
||||
return;
|
||||
}
|
||||
for (const child of batch) {
|
||||
await walk(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const entry of entries) {
|
||||
await walk(entry);
|
||||
}
|
||||
return collected;
|
||||
}
|
||||
|
||||
// Go's multipart parser rejects a form of more than 1000 parts, so a large
|
||||
// selection goes out in several requests.
|
||||
const uploadBatchSize = 500;
|
||||
// Longer file lists show this many rows and a count of the rest.
|
||||
const uploadListLimit = 200;
|
||||
// Set once files are uploaded while the modal stays open, so closing it reloads the listing.
|
||||
let uploadChangedListing = false;
|
||||
// The batch in flight, aborted when the modal closes.
|
||||
let activeUploadRequest = null;
|
||||
|
||||
function postUploadBatch(batch, currentPath, onProgress) {
|
||||
const formData = new FormData();
|
||||
batch.forEach(item => {
|
||||
formData.append('files', item.file);
|
||||
});
|
||||
if (batch.some(item => item.path !== item.file.name)) {
|
||||
formData.append('relativePaths', JSON.stringify(batch.map(item => item.path)));
|
||||
}
|
||||
formData.append('path', currentPath);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.upload.addEventListener('progress', function (e) {
|
||||
if (e.lengthComputable) {
|
||||
onProgress(e.loaded / e.total);
|
||||
}
|
||||
});
|
||||
xhr.addEventListener('load', function () {
|
||||
let response = null;
|
||||
try {
|
||||
response = JSON.parse(xhr.responseText);
|
||||
} catch (e) {
|
||||
// reported below
|
||||
}
|
||||
// Per-file failures come back with counts, even when all of them failed.
|
||||
if (response && typeof response.uploaded === 'number') {
|
||||
resolve(response);
|
||||
return;
|
||||
}
|
||||
if (xhr.status === 200) {
|
||||
reject(new Error('Upload completed but response format was unexpected'));
|
||||
return;
|
||||
}
|
||||
const errorMessage = (response && (response.error || response.message)) || `Server returned status ${xhr.status}`;
|
||||
reject(new Error(`Failed to upload files: ${errorMessage}`));
|
||||
});
|
||||
xhr.addEventListener('error', function () {
|
||||
reject(new Error('Failed to upload files. Please check your connection and try again.'));
|
||||
});
|
||||
xhr.addEventListener('abort', function () {
|
||||
reject(new Error('File upload was cancelled.'));
|
||||
});
|
||||
xhr.open('POST', basePath('/api/files/upload'));
|
||||
activeUploadRequest = xhr;
|
||||
xhr.send(formData);
|
||||
});
|
||||
}
|
||||
|
||||
// Submit upload file form
|
||||
async function submitUploadFile() {
|
||||
const fileInput = document.getElementById('fileInput');
|
||||
const currentPath = document.getElementById('uploadPath').value;
|
||||
const selected = selectedUploadFiles();
|
||||
|
||||
if (!fileInput.files || fileInput.files.length === 0) {
|
||||
showErrorMessage('Please select at least one file to upload');
|
||||
if (selected.length === 0) {
|
||||
showErrorMessage('Please select at least one file or folder to upload');
|
||||
return;
|
||||
}
|
||||
|
||||
const files = Array.from(fileInput.files);
|
||||
const totalSize = files.reduce((sum, file) => sum + file.size, 0);
|
||||
const totalSize = selected.reduce((sum, item) => sum + item.file.size, 0);
|
||||
|
||||
const maxSize = Number(document.getElementById('uploadFileForm').dataset.maxSize) || 0;
|
||||
if (maxSize > 0 && totalSize > maxSize) {
|
||||
@@ -1186,14 +1300,6 @@ async function submitUploadFile() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Individual file size validation removed - no limit per file
|
||||
|
||||
const formData = new FormData();
|
||||
files.forEach(file => {
|
||||
formData.append('files', file);
|
||||
});
|
||||
formData.append('path', currentPath);
|
||||
|
||||
// Show progress bar and disable button
|
||||
const progressContainer = document.getElementById('uploadProgress');
|
||||
const progressBar = progressContainer.querySelector('.progress-bar');
|
||||
@@ -1201,100 +1307,71 @@ async function submitUploadFile() {
|
||||
const submitButton = document.querySelector('#uploadFileModal .btn-primary');
|
||||
const originalText = submitButton.innerHTML;
|
||||
|
||||
const showProgress = percentComplete => {
|
||||
progressBar.style.width = percentComplete + '%';
|
||||
progressBar.setAttribute('aria-valuenow', percentComplete);
|
||||
progressBar.textContent = percentComplete + '%';
|
||||
uploadStatus.textContent = `Uploading ${selected.length} file(s)... ${percentComplete}%`;
|
||||
};
|
||||
|
||||
progressContainer.style.display = 'block';
|
||||
progressBar.style.width = '0%';
|
||||
progressBar.setAttribute('aria-valuenow', '0');
|
||||
progressBar.textContent = '0%';
|
||||
uploadStatus.textContent = `Uploading ${files.length} file(s)...`;
|
||||
showProgress(0);
|
||||
uploadStatus.textContent = `Uploading ${selected.length} file(s)...`;
|
||||
submitButton.disabled = true;
|
||||
submitButton.innerHTML = '<i class="bi bi-arrow-repeat icon-spin me-1"></i>Uploading...';
|
||||
|
||||
const result = { uploaded: 0, failed: 0, errors: [] };
|
||||
let failure = '';
|
||||
try {
|
||||
const xhr = new XMLHttpRequest();
|
||||
|
||||
// Handle progress
|
||||
xhr.upload.addEventListener('progress', function (e) {
|
||||
if (e.lengthComputable) {
|
||||
const percentComplete = Math.round((e.loaded / e.total) * 100);
|
||||
progressBar.style.width = percentComplete + '%';
|
||||
progressBar.setAttribute('aria-valuenow', percentComplete);
|
||||
progressBar.textContent = percentComplete + '%';
|
||||
uploadStatus.textContent = `Uploading ${files.length} file(s)... ${percentComplete}%`;
|
||||
let sentSize = 0;
|
||||
for (let start = 0; start < selected.length; start += uploadBatchSize) {
|
||||
const batch = selected.slice(start, start + uploadBatchSize);
|
||||
const batchSize = batch.reduce((sum, item) => sum + item.file.size, 0);
|
||||
const response = await postUploadBatch(batch, currentPath, fraction => {
|
||||
const done = totalSize > 0
|
||||
? (sentSize + fraction * batchSize) / totalSize
|
||||
: (start + fraction * batch.length) / selected.length;
|
||||
showProgress(Math.round(done * 100));
|
||||
});
|
||||
sentSize += batchSize;
|
||||
result.uploaded += response.uploaded;
|
||||
result.failed += response.failed;
|
||||
result.errors.push(...(response.errors || []));
|
||||
if (response.uploaded > 0) {
|
||||
uploadChangedListing = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Handle completion
|
||||
xhr.addEventListener('load', function () {
|
||||
if (xhr.status === 200) {
|
||||
try {
|
||||
const response = JSON.parse(xhr.responseText);
|
||||
|
||||
if (response.uploaded > 0) {
|
||||
if (response.failed === 0) {
|
||||
showSuccessMessage(`Successfully uploaded ${response.uploaded} file(s)`);
|
||||
} else {
|
||||
showSuccessMessage(response.message);
|
||||
// Show details of failed uploads
|
||||
if (response.errors && response.errors.length > 0) {
|
||||
console.warn('Upload errors:', response.errors);
|
||||
}
|
||||
}
|
||||
|
||||
// Hide modal and refresh page
|
||||
const modal = bootstrap.Modal.getInstance(document.getElementById('uploadFileModal'));
|
||||
modal.hide();
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1000);
|
||||
} else {
|
||||
let errorMessage = response.message || 'All file uploads failed';
|
||||
if (response.errors && response.errors.length > 0) {
|
||||
errorMessage += ': ' + response.errors.join(', ');
|
||||
}
|
||||
showErrorMessage(errorMessage);
|
||||
}
|
||||
} catch (e) {
|
||||
showErrorMessage('Upload completed but response format was unexpected');
|
||||
}
|
||||
progressContainer.style.display = 'none';
|
||||
} else {
|
||||
let errorMessage = 'Unknown error';
|
||||
try {
|
||||
const error = JSON.parse(xhr.responseText);
|
||||
errorMessage = error.error || error.message || errorMessage;
|
||||
} catch (e) {
|
||||
errorMessage = `Server returned status ${xhr.status}`;
|
||||
}
|
||||
showErrorMessage(`Failed to upload files: ${errorMessage}`);
|
||||
progressContainer.style.display = 'none';
|
||||
}
|
||||
});
|
||||
|
||||
// Handle errors
|
||||
xhr.addEventListener('error', function () {
|
||||
showErrorMessage('Failed to upload files. Please check your connection and try again.');
|
||||
progressContainer.style.display = 'none';
|
||||
});
|
||||
|
||||
// Handle abort
|
||||
xhr.addEventListener('abort', function () {
|
||||
showErrorMessage('File upload was cancelled.');
|
||||
progressContainer.style.display = 'none';
|
||||
});
|
||||
|
||||
// Send request
|
||||
xhr.open('POST', basePath('/api/files/upload'));
|
||||
xhr.send(formData);
|
||||
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Upload error:', error);
|
||||
showErrorMessage('Failed to upload files. Please try again.');
|
||||
progressContainer.style.display = 'none';
|
||||
} finally {
|
||||
// Re-enable the button
|
||||
submitButton.disabled = false;
|
||||
submitButton.innerHTML = originalText;
|
||||
uploadChangedListing = true;
|
||||
failure = error.message || 'Failed to upload files. Please try again.';
|
||||
if (result.uploaded > 0) {
|
||||
failure += ` (${result.uploaded} file(s) were uploaded before this)`;
|
||||
}
|
||||
}
|
||||
activeUploadRequest = null;
|
||||
|
||||
submitButton.disabled = false;
|
||||
submitButton.innerHTML = originalText;
|
||||
|
||||
if (!failure && result.failed === 0) {
|
||||
uploadChangedListing = false;
|
||||
progressContainer.style.display = 'none';
|
||||
showSuccessMessage(`Successfully uploaded ${result.uploaded} file(s)`);
|
||||
bootstrap.Modal.getInstance(document.getElementById('uploadFileModal')).hide();
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1000);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!failure) {
|
||||
failure = result.uploaded === 0 ? 'All file uploads failed' : `Uploaded ${result.uploaded} file(s), ${result.failed} failed`;
|
||||
}
|
||||
showErrorMessage(escapeHtml(failure));
|
||||
uploadStatus.innerHTML = `<div class="text-danger">${escapeHtml(failure)}</div>` +
|
||||
result.errors.slice(0, uploadListLimit).map(error => `<div class="text-break">${escapeHtml(error)}</div>`).join('') +
|
||||
(result.errors.length > uploadListLimit ? `<div>and ${result.errors.length - uploadListLimit} more</div>` : '');
|
||||
}
|
||||
|
||||
// Export file list to CSV
|
||||
@@ -1430,12 +1507,16 @@ function setupFileManagerEventHandlers() {
|
||||
}
|
||||
|
||||
// Handle file selection change to show preview
|
||||
const fileInput = document.getElementById('fileInput');
|
||||
if (fileInput) {
|
||||
fileInput.addEventListener('change', function (e) {
|
||||
updateFileListPreview();
|
||||
});
|
||||
}
|
||||
['fileInput', 'folderInput'].forEach(id => {
|
||||
const input = document.getElementById(id);
|
||||
if (input) {
|
||||
input.addEventListener('change', function (e) {
|
||||
uploadSelection++;
|
||||
droppedUploadFiles = null;
|
||||
updateFileListPreview();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Setup checkbox event listeners for file selection
|
||||
const checkboxes = document.querySelectorAll('.file-checkbox');
|
||||
@@ -1460,10 +1541,20 @@ function setupFileManagerEventHandlers() {
|
||||
const uploadFileModal = document.getElementById('uploadFileModal');
|
||||
if (uploadFileModal) {
|
||||
uploadFileModal.addEventListener('hidden.bs.modal', function () {
|
||||
const cancelled = activeUploadRequest;
|
||||
if (cancelled) {
|
||||
cancelled.abort();
|
||||
}
|
||||
if (cancelled || uploadChangedListing) {
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
const fileInput = document.getElementById('fileInput');
|
||||
const progressContainer = document.getElementById('uploadProgress');
|
||||
const fileListPreview = document.getElementById('fileListPreview');
|
||||
fileInput.value = '';
|
||||
document.getElementById('folderInput').value = '';
|
||||
droppedUploadFiles = null;
|
||||
progressContainer.style.display = 'none';
|
||||
fileListPreview.style.display = 'none';
|
||||
});
|
||||
@@ -1540,43 +1631,42 @@ function setupDragAndDrop() {
|
||||
}
|
||||
}
|
||||
|
||||
function handleDrop(e) {
|
||||
const dt = e.dataTransfer;
|
||||
const files = dt.files;
|
||||
|
||||
if (files.length > 0) {
|
||||
// Open upload modal and set files
|
||||
const fileInput = document.getElementById('fileInput');
|
||||
if (fileInput) {
|
||||
// Create a new FileList-like object
|
||||
const fileArray = Array.from(files);
|
||||
|
||||
// Set files to input (this is a bit tricky with file inputs)
|
||||
const dataTransfer = new DataTransfer();
|
||||
fileArray.forEach(file => dataTransfer.items.add(file));
|
||||
fileInput.files = dataTransfer.files;
|
||||
|
||||
// Update preview and show modal
|
||||
updateFileListPreview();
|
||||
const modal = new bootstrap.Modal(uploadModal);
|
||||
modal.show();
|
||||
async function handleDrop(e) {
|
||||
const selection = ++uploadSelection;
|
||||
let dropped;
|
||||
try {
|
||||
dropped = await collectDroppedFiles(e.dataTransfer, () => selection === uploadSelection);
|
||||
} catch (error) {
|
||||
console.error('Drop error:', error);
|
||||
if (selection === uploadSelection) {
|
||||
showErrorMessage('Failed to read the dropped files.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (selection !== uploadSelection || dropped.length === 0) {
|
||||
return;
|
||||
}
|
||||
document.getElementById('fileInput').value = '';
|
||||
document.getElementById('folderInput').value = '';
|
||||
droppedUploadFiles = dropped;
|
||||
updateFileListPreview();
|
||||
const modal = new bootstrap.Modal(uploadModal);
|
||||
modal.show();
|
||||
}
|
||||
}
|
||||
|
||||
// Update file list preview when files are selected
|
||||
function updateFileListPreview() {
|
||||
const fileInput = document.getElementById('fileInput');
|
||||
const fileListPreview = document.getElementById('fileListPreview');
|
||||
const selectedFilesList = document.getElementById('selectedFilesList');
|
||||
const selected = selectedUploadFiles();
|
||||
|
||||
if (!fileInput.files || fileInput.files.length === 0) {
|
||||
if (selected.length === 0) {
|
||||
fileListPreview.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
const files = Array.from(fileInput.files);
|
||||
const files = selected.map(item => item.file);
|
||||
const totalSize = files.reduce((sum, file) => sum + file.size, 0);
|
||||
|
||||
let html = `<div class="d-flex justify-content-between align-items-center mb-2">
|
||||
@@ -1584,16 +1674,19 @@ function updateFileListPreview() {
|
||||
<small class="text-muted">Total: ${formatBytes(totalSize)}</small>
|
||||
</div>`;
|
||||
|
||||
files.forEach((file, index) => {
|
||||
selected.slice(0, uploadListLimit).forEach(({ file, path }, index) => {
|
||||
const fileIcon = getFileIconByName(file.name);
|
||||
html += `<div class="d-flex justify-content-between align-items-center py-1 ${index > 0 ? 'border-top' : ''}">
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="bi ${fileIcon} me-2 text-muted"></i>
|
||||
<span class="text-truncate" style="max-width: 200px;" title="${file.name}">${file.name}</span>
|
||||
<span class="text-truncate" style="max-width: 400px;" title="${escapeHtmlForAttribute(path)}">${escapeHtml(path)}</span>
|
||||
</div>
|
||||
<small class="text-muted">${formatBytes(file.size)}</small>
|
||||
</div>`;
|
||||
});
|
||||
if (selected.length > uploadListLimit) {
|
||||
html += `<div class="border-top py-1 small text-muted">and ${selected.length - uploadListLimit} more</div>`;
|
||||
}
|
||||
|
||||
selectedFilesList.innerHTML = html;
|
||||
fileListPreview.style.display = 'block';
|
||||
|
||||
Binary file not shown.
@@ -313,7 +313,7 @@ templ FileBrowser(data dash.FileBrowserData) {
|
||||
<form id="uploadFileForm" enctype="multipart/form-data" data-max-size={ fmt.Sprint(data.UploadMaxSize) }>
|
||||
<div class="mb-3">
|
||||
<label for="fileInput" class="form-label">Select Files</label>
|
||||
<input type="file" class="form-control" id="fileInput" name="files" multiple required>
|
||||
<input type="file" class="form-control" id="fileInput" name="files" multiple>
|
||||
<div class="form-text">
|
||||
Choose one or more files to upload to the current directory. You can select multiple files by holding Ctrl (Cmd on Mac) while clicking.
|
||||
if data.UploadMaxSize > 0 {
|
||||
@@ -321,6 +321,13 @@ templ FileBrowser(data dash.FileBrowserData) {
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="folderInput" class="form-label">Or Select a Folder</label>
|
||||
<input type="file" class="form-control" id="folderInput" webkitdirectory multiple>
|
||||
<div class="form-text">
|
||||
Uploads every file in the folder, keeping its subfolders. Empty subfolders are skipped.
|
||||
</div>
|
||||
</div>
|
||||
<input type="hidden" id="uploadPath" name="path" value={ data.CurrentPath }>
|
||||
|
||||
<!-- File List Preview -->
|
||||
@@ -401,11 +408,6 @@ templ FileBrowser(data dash.FileBrowserData) {
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
// Initialize file manager event handlers from admin.js
|
||||
if (typeof setupFileManagerEventHandlers === 'function') {
|
||||
setupFileManagerEventHandlers();
|
||||
}
|
||||
});
|
||||
|
||||
// File browser specific functions
|
||||
|
||||
@@ -865,7 +865,7 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 94, "\"><div class=\"mb-3\"><label for=\"fileInput\" class=\"form-label\">Select Files</label> <input type=\"file\" class=\"form-control\" id=\"fileInput\" name=\"files\" multiple required><div class=\"form-text\">Choose one or more files to upload to the current directory. You can select multiple files by holding Ctrl (Cmd on Mac) while clicking. ")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 94, "\"><div class=\"mb-3\"><label for=\"fileInput\" class=\"form-label\">Select Files</label> <input type=\"file\" class=\"form-control\" id=\"fileInput\" name=\"files\" multiple><div class=\"form-text\">Choose one or more files to upload to the current directory. You can select multiple files by holding Ctrl (Cmd on Mac) while clicking. ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -888,20 +888,20 @@ func FileBrowser(data dash.FileBrowserData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 97, "</div></div><input type=\"hidden\" id=\"uploadPath\" name=\"path\" value=\"")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 97, "</div></div><div class=\"mb-3\"><label for=\"folderInput\" class=\"form-label\">Or Select a Folder</label> <input type=\"file\" class=\"form-control\" id=\"folderInput\" webkitdirectory multiple><div class=\"form-text\">Uploads every file in the folder, keeping its subfolders. Empty subfolders are skipped.</div></div><input type=\"hidden\" id=\"uploadPath\" name=\"path\" value=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var42 string
|
||||
templ_7745c5c3_Var42, templ_7745c5c3_Err = templruntime.NewAttributeExpression(data.CurrentPath).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/file_browser.templ`, Line: 324, Col: 79}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/file_browser.templ`, Line: 331, Col: 79}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var42)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, "\"><!-- File List Preview --><div id=\"fileListPreview\" class=\"mb-3\" style=\"display: none;\"><label class=\"form-label\">Selected Files:</label><div id=\"selectedFilesList\" class=\"border rounded p-2 bg-light\"><!-- Files will be listed here --></div></div><!-- Upload Progress --><div class=\"mb-3\" id=\"uploadProgress\" style=\"display: none;\"><label class=\"form-label\">Upload Progress:</label><div class=\"progress mb-2\"><div class=\"progress-bar progress-bar-striped progress-bar-animated\" role=\"progressbar\" style=\"width: 0%\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\">0%</div></div><div id=\"uploadStatus\" class=\"small text-muted\">Preparing upload...</div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"submitUploadFile()\"><i class=\"bi bi-upload me-1\"></i>Upload Files</button></div></div></div></div><!-- JavaScript for file browser functionality --><script>\n\tdocument.addEventListener('DOMContentLoaded', function() {\n\t\t// Format permissions in the main table\n\t\tdocument.querySelectorAll('.permissions-display').forEach(element => {\n\t\t\tconst mode = element.getAttribute('data-mode');\n\t\t\tconst isDirectory = element.getAttribute('data-is-directory') === 'true';\n\t\t\tif (mode) {\n\t\t\t\telement.textContent = formatPermissions(mode, isDirectory);\n\t\t\t}\n\t\t});\n\t\t\n\t\t// Handle file browser action buttons (download, view, properties, export-metadata, delete)\n\t\tdocument.addEventListener('click', function(e) {\n\t\t\tconst button = e.target.closest('[data-action]');\n\t\t\tif (!button) return;\n\t\t\t\n\t\t\tconst action = button.getAttribute('data-action');\n\t\t\tif (action === 'copy-url') {\n\t\t\t\tconst url = button.getAttribute('data-url');\n\t\t\t\tif (url) adminCopyToClipboard(url);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst path = button.getAttribute('data-path');\n\n\t\t\tif (!path) return;\n\t\t\t\n\t\t\tswitch(action) {\n\t\t\t\tcase 'download':\n\t\t\t\t\tdownloadFile(path);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'view':\n\t\t\t\t\tviewFile(path);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'properties':\n\t\t\t\t\tshowFileProperties(path);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'export-metadata':\n\t\t\t\t\texportMetadata(path);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'delete':\n\t\t\t\t\tconst fileName = path.split('/').pop();\n\t\t\t\t\tshowDeleteConfirm(fileName, function() {\n\t\t\t\t\t\tdeleteFile(path);\n\t\t\t\t\t}, `Are you sure you want to delete \"${fileName}\"? This action cannot be undone.`);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t\t\n\t\t// Initialize file manager event handlers from admin.js\n\t\tif (typeof setupFileManagerEventHandlers === 'function') {\n\t\t\tsetupFileManagerEventHandlers();\n\t\t}\n\t});\n\t\n\t// File browser specific functions\n\tfunction downloadFile(path) {\n\t\t// Open download URL in new tab\n\t\twindow.open((window.__BASE_PATH__ || '') + '/api/files/download?path=' + encodeURIComponent(path), '_blank');\n\t}\n\n\tfunction viewFile(path) {\n\t\t// Open file viewer in new tab\n\t\twindow.open((window.__BASE_PATH__ || '') + '/api/files/view?path=' + encodeURIComponent(path), '_blank');\n\t}\n\n\tfunction exportMetadata(path) {\n\t\t// Download metadata as an fs.meta.load-compatible .meta.gz\n\t\twindow.open((window.__BASE_PATH__ || '') + '/api/files/metadata?path=' + encodeURIComponent(path), '_blank');\n\t}\n\n\tfunction showFileProperties(path) {\n\t\t// Fetch file properties and show in modal\n\t\tfetch((window.__BASE_PATH__ || '') + '/api/files/properties?path=' + encodeURIComponent(path))\n\t\t\t.then(response => response.json())\n\t\t\t.then(data => {\n\t\t\t\tif (data.error) {\n\t\t\t\t\tshowAlert('Error loading file properties: ' + data.error, 'error');\n\t\t\t\t} else {\n\t\t\t\t\tdisplayFileProperties(data);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch(error => {\n\t\t\t\tconsole.error('Error fetching file properties:', error);\n\t\t\t\tshowAlert('Error loading file properties: ' + error.message, 'error');\n\t\t\t});\n\t}\n\t\n\tfunction displayFileProperties(data) {\n\t\t// Create a comprehensive modal for file properties\n\t\tconst modalHtml = '<div class=\"modal fade\" id=\"filePropertiesModal\" tabindex=\"-1\">' +\n\t\t\t'<div class=\"modal-dialog modal-lg\">' +\n\t\t\t'<div class=\"modal-content\">' +\n\t\t\t'<div class=\"modal-header\">' +\n\t\t\t'<h5 class=\"modal-title\"><i class=\"bi bi-info-circle me-2\"></i>Properties: ' + (data.name || 'Unknown') + '</h5>' +\n\t\t\t'<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>' +\n\t\t\t'</div>' +\n\t\t\t'<div class=\"modal-body\">' +\n\t\t\tcreateFilePropertiesContent(data) +\n\t\t\t'</div>' +\n\t\t\t'<div class=\"modal-footer\">' +\n\t\t\t'<button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button>' Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, "\"><!-- File List Preview --><div id=\"fileListPreview\" class=\"mb-3\" style=\"display: none;\"><label class=\"form-label\">Selected Files:</label><div id=\"selectedFilesList\" class=\"border rounded p-2 bg-light\"><!-- Files will be listed here --></div></div><!-- Upload Progress --><div class=\"mb-3\" id=\"uploadProgress\" style=\"display: none;\"><label class=\"form-label\">Upload Progress:</label><div class=\"progress mb-2\"><div class=\"progress-bar progress-bar-striped progress-bar-animated\" role=\"progressbar\" style=\"width: 0%\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\">0%</div></div><div id=\"uploadStatus\" class=\"small text-muted\">Preparing upload...</div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"submitUploadFile()\"><i class=\"bi bi-upload me-1\"></i>Upload Files</button></div></div></div></div><!-- JavaScript for file browser functionality --><script>\n\tdocument.addEventListener('DOMContentLoaded', function() {\n\t\t// Format permissions in the main table\n\t\tdocument.querySelectorAll('.permissions-display').forEach(element => {\n\t\t\tconst mode = element.getAttribute('data-mode');\n\t\t\tconst isDirectory = element.getAttribute('data-is-directory') === 'true';\n\t\t\tif (mode) {\n\t\t\t\telement.textContent = formatPermissions(mode, isDirectory);\n\t\t\t}\n\t\t});\n\t\t\n\t\t// Handle file browser action buttons (download, view, properties, export-metadata, delete)\n\t\tdocument.addEventListener('click', function(e) {\n\t\t\tconst button = e.target.closest('[data-action]');\n\t\t\tif (!button) return;\n\t\t\t\n\t\t\tconst action = button.getAttribute('data-action');\n\t\t\tif (action === 'copy-url') {\n\t\t\t\tconst url = button.getAttribute('data-url');\n\t\t\t\tif (url) adminCopyToClipboard(url);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst path = button.getAttribute('data-path');\n\n\t\t\tif (!path) return;\n\t\t\t\n\t\t\tswitch(action) {\n\t\t\t\tcase 'download':\n\t\t\t\t\tdownloadFile(path);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'view':\n\t\t\t\t\tviewFile(path);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'properties':\n\t\t\t\t\tshowFileProperties(path);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'export-metadata':\n\t\t\t\t\texportMetadata(path);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'delete':\n\t\t\t\t\tconst fileName = path.split('/').pop();\n\t\t\t\t\tshowDeleteConfirm(fileName, function() {\n\t\t\t\t\t\tdeleteFile(path);\n\t\t\t\t\t}, `Are you sure you want to delete \"${fileName}\"? This action cannot be undone.`);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t});\n\t\n\t// File browser specific functions\n\tfunction downloadFile(path) {\n\t\t// Open download URL in new tab\n\t\twindow.open((window.__BASE_PATH__ || '') + '/api/files/download?path=' + encodeURIComponent(path), '_blank');\n\t}\n\n\tfunction viewFile(path) {\n\t\t// Open file viewer in new tab\n\t\twindow.open((window.__BASE_PATH__ || '') + '/api/files/view?path=' + encodeURIComponent(path), '_blank');\n\t}\n\n\tfunction exportMetadata(path) {\n\t\t// Download metadata as an fs.meta.load-compatible .meta.gz\n\t\twindow.open((window.__BASE_PATH__ || '') + '/api/files/metadata?path=' + encodeURIComponent(path), '_blank');\n\t}\n\n\tfunction showFileProperties(path) {\n\t\t// Fetch file properties and show in modal\n\t\tfetch((window.__BASE_PATH__ || '') + '/api/files/properties?path=' + encodeURIComponent(path))\n\t\t\t.then(response => response.json())\n\t\t\t.then(data => {\n\t\t\t\tif (data.error) {\n\t\t\t\t\tshowAlert('Error loading file properties: ' + data.error, 'error');\n\t\t\t\t} else {\n\t\t\t\t\tdisplayFileProperties(data);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch(error => {\n\t\t\t\tconsole.error('Error fetching file properties:', error);\n\t\t\t\tshowAlert('Error loading file properties: ' + error.message, 'error');\n\t\t\t});\n\t}\n\t\n\tfunction displayFileProperties(data) {\n\t\t// Create a comprehensive modal for file properties\n\t\tconst modalHtml = '<div class=\"modal fade\" id=\"filePropertiesModal\" tabindex=\"-1\">' +\n\t\t\t'<div class=\"modal-dialog modal-lg\">' +\n\t\t\t'<div class=\"modal-content\">' +\n\t\t\t'<div class=\"modal-header\">' +\n\t\t\t'<h5 class=\"modal-title\"><i class=\"bi bi-info-circle me-2\"></i>Properties: ' + (data.name || 'Unknown') + '</h5>' +\n\t\t\t'<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button>' +\n\t\t\t'</div>' +\n\t\t\t'<div class=\"modal-body\">' +\n\t\t\tcreateFilePropertiesContent(data) +\n\t\t\t'</div>' +\n\t\t\t'<div class=\"modal-footer\">' +\n\t\t\t'<button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button>' +\n\t\t\t'</div>' +\n\t\t\t'</div>' +\n\t\t\t'</div>' +\n\t\t\t'</div>';\n\t\t\n\t\t// Remove existing modal if present\n\t\tconst existingModal = document.getElementById('filePrLine truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
background: #ddd;
|
||||
}
|
||||
|
||||
#fileElem {
|
||||
#fileElem, #dirElem {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@@ -94,6 +94,9 @@
|
||||
<label class="btn btn-default" for="fileElem">
|
||||
<span class="glyphicon glyphicon-cloud-upload" aria-hidden="true"></span> Upload
|
||||
</label>
|
||||
<label class="btn btn-default" for="dirElem">
|
||||
<span class="glyphicon glyphicon-folder-close" aria-hidden="true"></span> Upload Folder
|
||||
</label>
|
||||
</div>
|
||||
<ol class="breadcrumb">
|
||||
{{ range $entry := .Breadcrumbs }}
|
||||
@@ -108,6 +111,7 @@
|
||||
<div class="row" id="drop-area">
|
||||
<form class="upload-form">
|
||||
<input type="file" id="fileElem" multiple onchange="handleFiles(this.files)">
|
||||
<input type="file" id="dirElem" webkitdirectory multiple onchange="handleFiles(this.files)">
|
||||
|
||||
{{ if .EmptyFolder }}
|
||||
<div class="row add-files">
|
||||
@@ -219,10 +223,42 @@
|
||||
}
|
||||
|
||||
function handleDrop(e) {
|
||||
var dt = e.dataTransfer;
|
||||
var files = dt.files;
|
||||
collectDroppedFiles(e.dataTransfer).then(uploadItems, function (err) {
|
||||
alert('Failed to read the dropped files: ' + err);
|
||||
});
|
||||
}
|
||||
|
||||
handleFiles(files);
|
||||
// Lists the dropped files, walking into dropped folders. The entries must be
|
||||
// taken before the first await, while the drop event still exposes them.
|
||||
async function collectDroppedFiles(dataTransfer) {
|
||||
var entries = [...(dataTransfer.items || [])]
|
||||
.map(item => item.webkitGetAsEntry && item.webkitGetAsEntry())
|
||||
.filter(Boolean);
|
||||
if (entries.length === 0) {
|
||||
return [...dataTransfer.files].map(file => ({'file': file, 'path': file.name}));
|
||||
}
|
||||
var collected = [];
|
||||
async function walk(entry) {
|
||||
if (entry.isFile) {
|
||||
var file = await new Promise((resolve, reject) => entry.file(resolve, reject));
|
||||
collected.push({'file': file, 'path': entry.fullPath.replace(/^\/+/, '')});
|
||||
return;
|
||||
}
|
||||
var reader = entry.createReader();
|
||||
for (;;) {
|
||||
var batch = await new Promise((resolve, reject) => reader.readEntries(resolve, reject));
|
||||
if (batch.length === 0) {
|
||||
return;
|
||||
}
|
||||
for (let child of batch) {
|
||||
await walk(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let entry of entries) {
|
||||
await walk(entry);
|
||||
}
|
||||
return collected;
|
||||
}
|
||||
|
||||
function reloadPage() {
|
||||
@@ -232,14 +268,37 @@
|
||||
var uploadList = {};
|
||||
|
||||
function handleFiles(files) {
|
||||
files = [...files];
|
||||
files.forEach(startUpload);
|
||||
renderProgress();
|
||||
files.forEach(uploadFile);
|
||||
uploadItems([...files].map(file => ({'file': file, 'path': file.webkitRelativePath || file.name})));
|
||||
}
|
||||
|
||||
function startUpload(file, i) {
|
||||
uploadList[file.name] = {'name': file.name, 'percent': 0, 'finish': false};
|
||||
// A large folder uploads a few files at a time instead of opening a request per file,
|
||||
// and a selection made meanwhile joins the same queue.
|
||||
var uploadConcurrency = 4;
|
||||
var uploadQueue = [];
|
||||
var activeUploads = 0;
|
||||
|
||||
function uploadItems(items) {
|
||||
if (items.length === 0) {
|
||||
return;
|
||||
}
|
||||
items.forEach(startUpload);
|
||||
renderProgress();
|
||||
uploadQueue.push(...items);
|
||||
uploadNext();
|
||||
}
|
||||
|
||||
function uploadNext() {
|
||||
while (activeUploads < uploadConcurrency && uploadQueue.length > 0) {
|
||||
activeUploads++;
|
||||
uploadFile(uploadQueue.shift(), function () {
|
||||
activeUploads--;
|
||||
uploadNext();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function startUpload(item, i) {
|
||||
uploadList[item.path] = {'name': item.path, 'percent': 0, 'finish': false};
|
||||
}
|
||||
|
||||
function renderProgress() {
|
||||
@@ -253,7 +312,7 @@
|
||||
html += '<tr>\n<td>\n';
|
||||
html += '<div class="progress" style="margin-bottom: 2px;">\n';
|
||||
html += '<div class="progress-bar ' + progressBarClass + '" role="progressbar" aria-valuenow="' + '100" aria-valuemin="0" aria-valuemax="100" style="width:' + i.percent + '%;">';
|
||||
html += '<span style="margin-right: 10px;">' + i.name + '</span>' + i.percent + '%<\/div>';
|
||||
html += '<span style="margin-right: 10px;">' + escapeHtml(i.name) + '</span>' + i.percent + '%<\/div>';
|
||||
html += '<\/div>\n<\/td>\n<\/tr>\n';
|
||||
}
|
||||
html += '<\/table>\n';
|
||||
@@ -285,13 +344,35 @@
|
||||
}
|
||||
}
|
||||
|
||||
function uploadFile(file, i) {
|
||||
var url = window.location.href;
|
||||
function escapeHtml(text) {
|
||||
var div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// A file from a folder goes to its subfolder under the current directory,
|
||||
// which the filer creates on the first upload into it.
|
||||
function uploadUrl(path) {
|
||||
var dirs = path.split('/').slice(0, -1);
|
||||
if (dirs.length === 0) {
|
||||
return window.location.href;
|
||||
}
|
||||
var baseUrl = window.location.origin + window.location.pathname;
|
||||
if (!baseUrl.endsWith('/')) {
|
||||
baseUrl += '/';
|
||||
}
|
||||
return baseUrl + dirs.map(encodeURIComponent).join('/') + '/' + window.location.search;
|
||||
}
|
||||
|
||||
function uploadFile(item, done) {
|
||||
var file = item.file;
|
||||
var url = uploadUrl(item.path);
|
||||
var xhr = new XMLHttpRequest();
|
||||
var fileName = file.name;
|
||||
var fileName = item.path;
|
||||
xhr.onreadystatechange = function() {
|
||||
if (xhr.readyState == XMLHttpRequest.DONE) {
|
||||
finishUpload(fileName)
|
||||
finishUpload(fileName);
|
||||
done();
|
||||
}
|
||||
}
|
||||
xhr.upload.addEventListener('progress', function(e) {
|
||||
|
||||
Reference in new issue
Block a user