Skip to content

SeaweedFS is a distributed storage system for object storage (S3), file systems, Iceberg table buckets, and Lance vector buckets, designed to handle billions of files with O(1) disk access and effortless horizontal scaling.

filer UI, admin: upload a folder (#12371)

Chris Lu2ec0623073c5
diff --git a/weed/admin/handlers/file_browser_handlers.go b/weed/admin/handlers/file_browser_handlers.go
index fb5f122b72..dbe49b9f9c 100644
--- a/weed/admin/handlers/file_browser_handlers.go
+++ b/weed/admin/handlers/file_browser_handlers.go
@@ -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.
diff --git a/weed/admin/handlers/file_browser_handlers_test.go b/weed/admin/handlers/file_browser_handlers_test.go
index 179be2a6a0..1566ebacb3 100644
--- a/weed/admin/handlers/file_browser_handlers_test.go
+++ b/weed/admin/handlers/file_browser_handlers_test.go
@@ -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())
+ }
+}
diff --git a/weed/admin/static/js/admin.js b/weed/admin/static/js/admin.js
index 77681f26fc..ebabb25a32 100644
--- a/weed/admin/static/js/admin.js
+++ b/weed/admin/static/js/admin.js
@@ -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}%`;
- }
- });
-
- // 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';
+ 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 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.');
+ 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';
- } finally {
- // Re-enable the button
- submitButton.disabled = false;
- submitButton.innerHTML = originalText;
+ 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';
diff --git a/weed/admin/static_gz/js/admin.js.gz b/weed/admin/static_gz/js/admin.js.gz
index d6a6220718..328f9f92f0 100644
Binary files a/weed/admin/static_gz/js/admin.js.gz and b/weed/admin/static_gz/js/admin.js.gz differ
diff --git a/weed/admin/view/app/file_browser.templ b/weed/admin/view/app/file_browser.templ
index 7dc84c9069..24db7870df 100644
--- a/weed/admin/view/app/file_browser.templ
+++ b/weed/admin/view/app/file_browser.templ
@@ -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
diff --git a/weed/admin/view/app/file_browser_templ.go b/weed/admin/view/app/file_browser_templ.go
index f994bdd27a..f2a556bb15 100644
--- a/weed/admin/view/app/file_browser_templ.go
+++ b/weed/admin/view/app/file_browser_templ.go
@@ -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>' +\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('filePropertiesModal');\n\t\tif (existingModal) {\n\t\t\texistingModal.remove();\n\t\t}\n\t\t\n\t\t// Add modal to body and show\n\t\tdocument.body.insertAdjacentHTML('beforeend', modalHtml);\n\t\tconst modal = new bootstrap.Modal(document.getElementById('filePropertiesModal'));\n\t\tmodal.show();\n\t\t\n\t\t// Remove modal when hidden\n\t\tdocument.getElementById('filePropertiesModal').addEventListener('hidden.bs.modal', function() {\n\t\t\tthis.remove();\n\t\t});\n\t}\n\t\n\tfunction createFilePropertiesContent(data) {\n\t\tlet html = '<div class=\"row\">' +\n\t\t\t'<div class=\"col-12\">' +\n\t\t\t'<h6 class=\"text-primary\"><i class=\"bi bi-file-earmark me-1\"></i>Basic Information</h6>' +\n\t\t\t'<table class=\"table table-sm\">' +\n\t\t\t'<tr><td style=\"width: 120px;\"><strong>Name:</strong></td><td>' + (data.name || 'N/A') + '</td></tr>' +\n\t\t\t'<tr><td><strong>Full Path:</strong></td><td><code class=\"text-break\">' + (data.full_path || 'N/A') + '</code></td></tr>' +\n\t\t\t'<tr><td><strong>Type:</strong></td><td>' + (data.is_directory ? 'Directory' : 'File') + '</td></tr>';\n\t\t\n\t\tif (!data.is_directory) {\n\t\t\thtml += '<tr><td><strong>Size:</strong></td><td>' + (data.size_formatted || (data.size ? formatBytes(data.size) : 'N/A')) + '</td></tr>' +\n\t\t\t\t'<tr><td><strong>MIME Type:</strong></td><td>' + (data.mime_type || 'N/A') + '</td></tr>';\n\t\t\tif (data.object_url) {\n\t\t\t\thtml += '<tr><td><strong>Object URL:</strong></td><td><code class=\"text-break\">' + data.object_url + '</code>' +\n\t\t\t\t\t' <button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" title=\"Copy S3 URL\" data-action=\"copy-url\" data-url=\"' + data.object_url + '\"><i class=\"bi bi-copy\"></i></button></td></tr>';\n\t\t\t}\n\t\t}\n\t\t\n\t\thtml += '</table>' +\n\t\t\t'</div>' +\n\t\t\t'</div>' +\n\t\t\t'<div class=\"row\">' +\n\t\t\t'<div class=\"col-md-6\">' +\n\t\t\t'<h6 class=\"text-primary\"><i class=\"bi bi-clock me-1\"></i>Timestamps</h6>' +\n\t\t\t'<table class=\"table table-sm\">';\n\t\t\n\t\tif (data.modified_time) {\n\t\t\thtml += '<tr><td><strong>Modified:</strong></td><td>' + data.modified_time + '</td></tr>';\n\t\t}\n\t\tif (data.created_time) {\n\t\t\thtml += '<tr><td><strong>Created:</strong></td><td>' + data.created_time + '</td></tr>';\n\t\t}\n\t\t\n\t\thtml += '</table>' +\n\t\t\t'</div>' +\n\t\t\t'<div class=\"col-md-6\">' +\n\t\t\t'<h6 class=\"text-primary\"><i class=\"bi bi-shield me-1\"></i>Permissions</h6>' +\n\t\t\t'<table class=\"table table-sm\">';\n\t\t\n\t\tif (data.file_mode) {\n\t\t\tconst rwxPermissions = formatPermissions(data.file_mode, data.is_directory);\n\t\t\thtml += '<tr><td><strong>Permissions:</strong></td><td><code>' + rwxPermissions + '</code></td></tr>';\n\t\t}\n\t\tif (data.uid !== undefined) {\n\t\t\thtml += '<tr><td><strong>User ID:</strong></td><td>' + data.uid + '</td></tr>';\n\t\t}\n\t\tif (data.gid !== undefined) {\n\t\t\thtml += '<tr><td><strong>Group ID:</strong></td><td>' + data.gid + '</td></tr>';\n\t\t}\n\t\t\n\t\thtml += '</table>' +\n\t\t\t'</div>' +\n\t\t\t'</div>';\n\t\t\n\t\t// Add advanced info\n\t\thtml += '<div class=\"row\">' +\n\t\t\t'<div class=\"col-12\">' +\n\t\t\t'<h6 class=\"text-primary\"><i class=\"bi bi-gear me-1\"></i>Advanced</h6>' +\n\t\t\t'<table class=\"table table-sm\">';\n\t\t\n\t\tif (data.chunk_count) {\n\t\t\thtml += '<tr><td style=\"width: 120px;\"><strong>Chunks:</strong></td><td>' + data.chunk_count + '</td></tr>';\n\t\t}\n\t\tif (data.ttl_formatted) {\n\t\t\thtml += '<tr><td><strong>TTL:</strong></td><td>' + data.ttl_formatted + '</td></tr>';\n\t\t}\n\t\t\n\t\thtml += '</table>' +\n\t\t\t'</div>' +\n\t\t\t'</div>';\n\t\t\n\t\t// Add chunk details if available (show top 5)\n\t\tif (data.chunks && data.chunks.length > 0) {\n\t\t\tconst chunksToShow = data.chunks.slice(0, 5);\n\t\t\thtml += '<div class=\"row mt-3\">' +\n\t\t\t\t'<div class=\"col-12\">' +\n\t\t\t\t'<h6 class=\"text-primary\"><i class=\"bi bi-puzzle me-1\"></i>Chunk Details' +\n\t\t\t\t(data.chunk_count > 5 ? ' (Top 5 of ' + data.chunk_count + ')' : ' (' + data.chunk_count + ')') +\n\t\t\t\t'</h6>' +\n\t\t\t\t'<div class=\"table-responsive\" style=\"max-height: 200px; overflow-y: auto;\">' +\n\t\t\t\t'<table class=\"table table-sm table-striped\">' +\n\t\t\t\t'<thead>' +\n\t\t\t\t'<tr>' +\n\t\t\t\t'<th>File ID</th>' +\n\t\t\t\t'<th>Offset</th>' +\n\t\t\t\t'<th>Size</th>' +\n\t\t\t\t'<th>ETag</th>' +\n\t\t\t\t'</tr>' +\n\t\t\t\t'</thead>' +\n\t\t\t\t'<tbody>';\n\t\t\t\n\t\t\tchunksToShow.forEach(chunk => {\n\t\t\t\thtml += '<tr>' +\n\t\t\t\t\t'<td><code class=\"small\">' + (chunk.file_id || 'N/A') + '</code></td>' +\n\t\t\t\t\t'<td>' + formatBytes(chunk.offset || 0) + '</td>' +\n\t\t\t\t\t'<td>' + formatBytes(chunk.size || 0) + '</td>' +\n\t\t\t\t\t'<td><code class=\"small\">' + (chunk.e_tag || 'N/A') + '</code></td>' +\n\t\t\t\t\t'</tr>';\n\t\t\t});\n\t\t\t\n\t\t\thtml += '</tbody>' +\n\t\t\t\t'</table>' +\n\t\t\t\t'</div>' +\n\t\t\t\t'</div>' +\n\t\t\t\t'</div>';\n\t\t}\n\t\t\n\t\t// Add extended attributes if present\n\t\tif (data.extended && Object.keys(data.extended).length > 0) {\n\t\t\thtml += '<div class=\"row\">' +\n\t\t\t\t'<div class=\"col-12\">' +\n\t\t\t\t'<h6 class=\"text-primary\"><i class=\"bi bi-tags me-1\"></i>Extended Attributes</h6>' +\n\t\t\t\t'<table class=\"table table-sm\">';\n\t\t\t\n\t\t\tfor (const [key, value] of Object.entries(data.extended)) {\n\t\t\t\thtml += '<tr><td><strong>' + key + ':</strong></td><td>' + value + '</td></tr>';\n\t\t\t}\n\t\t\t\n\t\t\thtml += '</table>' +\n\t\t\t\t'</div>' +\n\t\t\t\t'</div>';\n\t\t}\n\t\t\n\t\treturn html;\n\t}\n\t\n\tfunction uploadFile() {\n\t\tconst modal = new bootstrap.Modal(document.getElementById('uploadFileModal'));\n\t\tmodal.show();\n\t}\n\t\n\tfunction toggleSelectAll() {\n\t\tconst selectAllCheckbox = document.getElementById('selectAll');\n\t\tconst checkboxes = document.querySelectorAll('.file-checkbox');\n\t\t\n\t\tcheckboxes.forEach(checkbox => {\n\t\t\tcheckbox.checked = selectAllCheckbox.checked;\n\t\t});\n\t\t\n\t\tupdateDeleteSelectedButton();\n\t}\n\t\n\tfunction updateDeleteSelectedButton() {\n\t\tconst checkboxes = document.querySelectorAll('.file-checkbox:checked');\n\t\tconst deleteBtn = document.getElementById('deleteSelectedBtn');\n\t\t\n\t\tif (checkboxes.length > 0) {\n\t\t\tdeleteBtn.style.display = 'inline-block';\n\t\t} else {\n\t\t\tdeleteBtn.style.display = 'none';\n\t\t}\n\t}\n\t\n\t// Helper function to format bytes\n\tfunction formatBytes(bytes) {\n\t\tif (bytes === 0) return '0 Bytes';\n\t\tconst k = 1024;\n\t\tconst sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n\t\tconst i = Math.floor(Math.log(bytes) / Math.log(k));\n\t\treturn parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n\t}\n\t\n\t// Helper function to format permissions in rwxrwxrwx format\n\tfunction formatPermissions(mode, isDirectory) {\n\t\t// Check if mode is already in rwxrwxrwx format (e.g., \"drwxr-xr-x\" or \"-rw-r--r--\")\n\t\tif (mode && (mode.startsWith('d') || mode.startsWith('-') || mode.startsWith('l')) && mode.length === 10) {\n\t\t\treturn mode; // Already formatted\n\t\t}\n\t\t\n\t\t// Convert to number - could be octal string or decimal\n\t\tlet permissions;\n\t\tif (typeof mode === 'string') {\n\t\t\t// Try parsing as octal first, then decimal\n\t\t\tif (mode.startsWith('0') && mode.length <= 4) {\n\t\t\t\tpermissions = parseInt(mode, 8);\n\t\t\t} else {\n\t\t\t\tpermissions = parseInt(mode, 10);\n\t\t\t}\n\t\t} else {\n\t\t\tpermissions = parseInt(mode, 10);\n\t\t}\n\t\t\n\t\tif (isNaN(permissions)) {\n\t\t\treturn isDirectory ? 'drwxr-xr-x' : '-rw-r--r--'; // Default fallback\n\t\t}\n\t\t\n\t\t// Handle Go's os.ModeDir conversion\n\t\t// Go's os.ModeDir is 0x80000000 (2147483648), but Unix S_IFDIR is 0o40000 (16384)\n\t\tlet fileType = '-';\n\t\t\n\t\t// Check for Go's os.ModeDir flag\n\t\tif (permissions & 0x80000000) {\n\t\t\tfileType = 'd';\n\t\t}\n\t\t// Check for standard Unix file type bits\n\t\telse if ((permissions & 0xF000) === 0x4000) { // S_IFDIR (0o40000)\n\t\t\tfileType = 'd';\n\t\t} else if ((permissions & 0xF000) === 0x8000) { // S_IFREG (0o100000)\n\t\t\tfileType = '-';\n\t\t} else if ((permissions & 0xF000) === 0xA000) { // S_IFLNK (0o120000)\n\t\t\tfileType = 'l';\n\t\t} else if ((permissions & 0xF000) === 0x2000) { // S_IFCHR (0o020000)\n\t\t\tfileType = 'c';\n\t\t} else if ((permissions & 0xF000) === 0x6000) { // S_IFBLK (0o060000)\n\t\t\tfileType = 'b';\n\t\t} else if ((permissions & 0xF000) === 0x1000) { // S_IFIFO (0o010000)\n\t\t\tfileType = 'p';\n\t\t} else if ((permissions & 0xF000) === 0xC000) { // S_IFSOCK (0o140000)\n\t\t\tfileType = 's';\n\t\t}\n\t\t// Fallback to isDirectory parameter if file type detection fails\n\t\telse if (isDirectory) {\n\t\t\tfileType = 'd';\n\t\t}\n\t\t\n\t\t// Permission bits (always use the lower 12 bits for permissions)\n\t\tconst owner = (permissions >> 6) & 7;\n\t\tconst group = (permissions >> 3) & 7;\n\t\tconst others = permissions & 7;\n\t\t\n\t\t// Convert number to rwx format\n\t\tfunction numToRwx(num) {\n\t\t\tconst r = (num & 4) ? 'r' : '-';\n\t\t\tconst w = (num & 2) ? 'w' : '-';\n\t\t\tconst x = (num & 1) ? 'x' : '-';\n\t\t\treturn r + w + x;\n\t\t}\n\t\t\n\t\treturn fileType + numToRwx(owner) + numToRwx(group) + numToRwx(others);\n\t}\n\t\n\tfunction exportFileList() {\n\t\t// Simple CSV export of file list\n\t\tconst rows = Array.from(document.querySelectorAll('#fileTable tbody tr')).map(row => {\n\t\t\tconst cells = row.querySelectorAll('td');\n\t\t\tif (cells.length > 1) {\n\t\t\t\treturn {\n\t\t\t\t\tname: cells[1].textContent.trim(),\n\t\t\t\t\tsize: cells[2].textContent.trim(),\n\t\t\t\t\ttype: cells[3].textContent.trim(),\n\t\t\t\t\tmodified: cells[4].textContent.trim(),\n\t\t\t\t\tpermissions: cells[5].textContent.trim()\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn null;\n\t\t}).filter(row => row !== null);\n\t\t\n\t\tconst csvContent = \"data:text/csv;charset=utf-8,\" + \n\t\t\t\"Name,Size,Type,Modified,Permissions\\n\" +\n\t\t\trows.map(r => '\"' + r.name + '\",\"' + r.size + '\",\"' + r.type + '\",\"' + r.modified + '\",\"' + r.permissions + '\"').join(\"\\n\");\n\t\t\n\t\tconst encodedUri = encodeURI(csvContent);\n\t\tconst link = document.createElement(\"a\");\n\t\tlink.setAttribute(\"href\", encodedUri);\n\t\tlink.setAttribute(\"download\", \"files.csv\");\n\t\tdocument.body.appendChild(link);\n\t\tlink.click();\n\t\tdocument.body.removeChild(link);\n\t}\n\t\n\t// Handle file checkbox changes\n\tdocument.addEventListener('change', function(e) {\n\t\tif (e.target.classList.contains('file-checkbox')) {\n\t\t\tupdateDeleteSelectedButton();\n\t\t}\n\t});\n\t</script>")
+ 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('filePropertiesModal');\n\t\tif (existingModal) {\n\t\t\texistingModal.remove();\n\t\t}\n\t\t\n\t\t// Add modal to body and show\n\t\tdocument.body.insertAdjacentHTML('beforeend', modalHtml);\n\t\tconst modal = new bootstrap.Modal(document.getElementById('filePropertiesModal'));\n\t\tmodal.show();\n\t\t\n\t\t// Remove modal when hidden\n\t\tdocument.getElementById('filePropertiesModal').addEventListener('hidden.bs.modal', function() {\n\t\t\tthis.remove();\n\t\t});\n\t}\n\t\n\tfunction createFilePropertiesContent(data) {\n\t\tlet html = '<div class=\"row\">' +\n\t\t\t'<div class=\"col-12\">' +\n\t\t\t'<h6 class=\"text-primary\"><i class=\"bi bi-file-earmark me-1\"></i>Basic Information</h6>' +\n\t\t\t'<table class=\"table table-sm\">' +\n\t\t\t'<tr><td style=\"width: 120px;\"><strong>Name:</strong></td><td>' + (data.name || 'N/A') + '</td></tr>' +\n\t\t\t'<tr><td><strong>Full Path:</strong></td><td><code class=\"text-break\">' + (data.full_path || 'N/A') + '</code></td></tr>' +\n\t\t\t'<tr><td><strong>Type:</strong></td><td>' + (data.is_directory ? 'Directory' : 'File') + '</td></tr>';\n\t\t\n\t\tif (!data.is_directory) {\n\t\t\thtml += '<tr><td><strong>Size:</strong></td><td>' + (data.size_formatted || (data.size ? formatBytes(data.size) : 'N/A')) + '</td></tr>' +\n\t\t\t\t'<tr><td><strong>MIME Type:</strong></td><td>' + (data.mime_type || 'N/A') + '</td></tr>';\n\t\t\tif (data.object_url) {\n\t\t\t\thtml += '<tr><td><strong>Object URL:</strong></td><td><code class=\"text-break\">' + data.object_url + '</code>' +\n\t\t\t\t\t' <button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" title=\"Copy S3 URL\" data-action=\"copy-url\" data-url=\"' + data.object_url + '\"><i class=\"bi bi-copy\"></i></button></td></tr>';\n\t\t\t}\n\t\t}\n\t\t\n\t\thtml += '</table>' +\n\t\t\t'</div>' +\n\t\t\t'</div>' +\n\t\t\t'<div class=\"row\">' +\n\t\t\t'<div class=\"col-md-6\">' +\n\t\t\t'<h6 class=\"text-primary\"><i class=\"bi bi-clock me-1\"></i>Timestamps</h6>' +\n\t\t\t'<table class=\"table table-sm\">';\n\t\t\n\t\tif (data.modified_time) {\n\t\t\thtml += '<tr><td><strong>Modified:</strong></td><td>' + data.modified_time + '</td></tr>';\n\t\t}\n\t\tif (data.created_time) {\n\t\t\thtml += '<tr><td><strong>Created:</strong></td><td>' + data.created_time + '</td></tr>';\n\t\t}\n\t\t\n\t\thtml += '</table>' +\n\t\t\t'</div>' +\n\t\t\t'<div class=\"col-md-6\">' +\n\t\t\t'<h6 class=\"text-primary\"><i class=\"bi bi-shield me-1\"></i>Permissions</h6>' +\n\t\t\t'<table class=\"table table-sm\">';\n\t\t\n\t\tif (data.file_mode) {\n\t\t\tconst rwxPermissions = formatPermissions(data.file_mode, data.is_directory);\n\t\t\thtml += '<tr><td><strong>Permissions:</strong></td><td><code>' + rwxPermissions + '</code></td></tr>';\n\t\t}\n\t\tif (data.uid !== undefined) {\n\t\t\thtml += '<tr><td><strong>User ID:</strong></td><td>' + data.uid + '</td></tr>';\n\t\t}\n\t\tif (data.gid !== undefined) {\n\t\t\thtml += '<tr><td><strong>Group ID:</strong></td><td>' + data.gid + '</td></tr>';\n\t\t}\n\t\t\n\t\thtml += '</table>' +\n\t\t\t'</div>' +\n\t\t\t'</div>';\n\t\t\n\t\t// Add advanced info\n\t\thtml += '<div class=\"row\">' +\n\t\t\t'<div class=\"col-12\">' +\n\t\t\t'<h6 class=\"text-primary\"><i class=\"bi bi-gear me-1\"></i>Advanced</h6>' +\n\t\t\t'<table class=\"table table-sm\">';\n\t\t\n\t\tif (data.chunk_count) {\n\t\t\thtml += '<tr><td style=\"width: 120px;\"><strong>Chunks:</strong></td><td>' + data.chunk_count + '</td></tr>';\n\t\t}\n\t\tif (data.ttl_formatted) {\n\t\t\thtml += '<tr><td><strong>TTL:</strong></td><td>' + data.ttl_formatted + '</td></tr>';\n\t\t}\n\t\t\n\t\thtml += '</table>' +\n\t\t\t'</div>' +\n\t\t\t'</div>';\n\t\t\n\t\t// Add chunk details if available (show top 5)\n\t\tif (data.chunks && data.chunks.length > 0) {\n\t\t\tconst chunksToShow = data.chunks.slice(0, 5);\n\t\t\thtml += '<div class=\"row mt-3\">' +\n\t\t\t\t'<div class=\"col-12\">' +\n\t\t\t\t'<h6 class=\"text-primary\"><i class=\"bi bi-puzzle me-1\"></i>Chunk Details' +\n\t\t\t\t(data.chunk_count > 5 ? ' (Top 5 of ' + data.chunk_count + ')' : ' (' + data.chunk_count + ')') +\n\t\t\t\t'</h6>' +\n\t\t\t\t'<div class=\"table-responsive\" style=\"max-height: 200px; overflow-y: auto;\">' +\n\t\t\t\t'<table class=\"table table-sm table-striped\">' +\n\t\t\t\t'<thead>' +\n\t\t\t\t'<tr>' +\n\t\t\t\t'<th>File ID</th>' +\n\t\t\t\t'<th>Offset</th>' +\n\t\t\t\t'<th>Size</th>' +\n\t\t\t\t'<th>ETag</th>' +\n\t\t\t\t'</tr>' +\n\t\t\t\t'</thead>' +\n\t\t\t\t'<tbody>';\n\t\t\t\n\t\t\tchunksToShow.forEach(chunk => {\n\t\t\t\thtml += '<tr>' +\n\t\t\t\t\t'<td><code class=\"small\">' + (chunk.file_id || 'N/A') + '</code></td>' +\n\t\t\t\t\t'<td>' + formatBytes(chunk.offset || 0) + '</td>' +\n\t\t\t\t\t'<td>' + formatBytes(chunk.size || 0) + '</td>' +\n\t\t\t\t\t'<td><code class=\"small\">' + (chunk.e_tag || 'N/A') + '</code></td>' +\n\t\t\t\t\t'</tr>';\n\t\t\t});\n\t\t\t\n\t\t\thtml += '</tbody>' +\n\t\t\t\t'</table>' +\n\t\t\t\t'</div>' +\n\t\t\t\t'</div>' +\n\t\t\t\t'</div>';\n\t\t}\n\t\t\n\t\t// Add extended attributes if present\n\t\tif (data.extended && Object.keys(data.extended).length > 0) {\n\t\t\thtml += '<div class=\"row\">' +\n\t\t\t\t'<div class=\"col-12\">' +\n\t\t\t\t'<h6 class=\"text-primary\"><i class=\"bi bi-tags me-1\"></i>Extended Attributes</h6>' +\n\t\t\t\t'<table class=\"table table-sm\">';\n\t\t\t\n\t\t\tfor (const [key, value] of Object.entries(data.extended)) {\n\t\t\t\thtml += '<tr><td><strong>' + key + ':</strong></td><td>' + value + '</td></tr>';\n\t\t\t}\n\t\t\t\n\t\t\thtml += '</table>' +\n\t\t\t\t'</div>' +\n\t\t\t\t'</div>';\n\t\t}\n\t\t\n\t\treturn html;\n\t}\n\t\n\tfunction uploadFile() {\n\t\tconst modal = new bootstrap.Modal(document.getElementById('uploadFileModal'));\n\t\tmodal.show();\n\t}\n\t\n\tfunction toggleSelectAll() {\n\t\tconst selectAllCheckbox = document.getElementById('selectAll');\n\t\tconst checkboxes = document.querySelectorAll('.file-checkbox');\n\t\t\n\t\tcheckboxes.forEach(checkbox => {\n\t\t\tcheckbox.checked = selectAllCheckbox.checked;\n\t\t});\n\t\t\n\t\tupdateDeleteSelectedButton();\n\t}\n\t\n\tfunction updateDeleteSelectedButton() {\n\t\tconst checkboxes = document.querySelectorAll('.file-checkbox:checked');\n\t\tconst deleteBtn = document.getElementById('deleteSelectedBtn');\n\t\t\n\t\tif (checkboxes.length > 0) {\n\t\t\tdeleteBtn.style.display = 'inline-block';\n\t\t} else {\n\t\t\tdeleteBtn.style.display = 'none';\n\t\t}\n\t}\n\t\n\t// Helper function to format bytes\n\tfunction formatBytes(bytes) {\n\t\tif (bytes === 0) return '0 Bytes';\n\t\tconst k = 1024;\n\t\tconst sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n\t\tconst i = Math.floor(Math.log(bytes) / Math.log(k));\n\t\treturn parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n\t}\n\t\n\t// Helper function to format permissions in rwxrwxrwx format\n\tfunction formatPermissions(mode, isDirectory) {\n\t\t// Check if mode is already in rwxrwxrwx format (e.g., \"drwxr-xr-x\" or \"-rw-r--r--\")\n\t\tif (mode && (mode.startsWith('d') || mode.startsWith('-') || mode.startsWith('l')) && mode.length === 10) {\n\t\t\treturn mode; // Already formatted\n\t\t}\n\t\t\n\t\t// Convert to number - could be octal string or decimal\n\t\tlet permissions;\n\t\tif (typeof mode === 'string') {\n\t\t\t// Try parsing as octal first, then decimal\n\t\t\tif (mode.startsWith('0') && mode.length <= 4) {\n\t\t\t\tpermissions = parseInt(mode, 8);\n\t\t\t} else {\n\t\t\t\tpermissions = parseInt(mode, 10);\n\t\t\t}\n\t\t} else {\n\t\t\tpermissions = parseInt(mode, 10);\n\t\t}\n\t\t\n\t\tif (isNaN(permissions)) {\n\t\t\treturn isDirectory ? 'drwxr-xr-x' : '-rw-r--r--'; // Default fallback\n\t\t}\n\t\t\n\t\t// Handle Go's os.ModeDir conversion\n\t\t// Go's os.ModeDir is 0x80000000 (2147483648), but Unix S_IFDIR is 0o40000 (16384)\n\t\tlet fileType = '-';\n\t\t\n\t\t// Check for Go's os.ModeDir flag\n\t\tif (permissions & 0x80000000) {\n\t\t\tfileType = 'd';\n\t\t}\n\t\t// Check for standard Unix file type bits\n\t\telse if ((permissions & 0xF000) === 0x4000) { // S_IFDIR (0o40000)\n\t\t\tfileType = 'd';\n\t\t} else if ((permissions & 0xF000) === 0x8000) { // S_IFREG (0o100000)\n\t\t\tfileType = '-';\n\t\t} else if ((permissions & 0xF000) === 0xA000) { // S_IFLNK (0o120000)\n\t\t\tfileType = 'l';\n\t\t} else if ((permissions & 0xF000) === 0x2000) { // S_IFCHR (0o020000)\n\t\t\tfileType = 'c';\n\t\t} else if ((permissions & 0xF000) === 0x6000) { // S_IFBLK (0o060000)\n\t\t\tfileType = 'b';\n\t\t} else if ((permissions & 0xF000) === 0x1000) { // S_IFIFO (0o010000)\n\t\t\tfileType = 'p';\n\t\t} else if ((permissions & 0xF000) === 0xC000) { // S_IFSOCK (0o140000)\n\t\t\tfileType = 's';\n\t\t}\n\t\t// Fallback to isDirectory parameter if file type detection fails\n\t\telse if (isDirectory) {\n\t\t\tfileType = 'd';\n\t\t}\n\t\t\n\t\t// Permission bits (always use the lower 12 bits for permissions)\n\t\tconst owner = (permissions >> 6) & 7;\n\t\tconst group = (permissions >> 3) & 7;\n\t\tconst others = permissions & 7;\n\t\t\n\t\t// Convert number to rwx format\n\t\tfunction numToRwx(num) {\n\t\t\tconst r = (num & 4) ? 'r' : '-';\n\t\t\tconst w = (num & 2) ? 'w' : '-';\n\t\t\tconst x = (num & 1) ? 'x' : '-';\n\t\t\treturn r + w + x;\n\t\t}\n\t\t\n\t\treturn fileType + numToRwx(owner) + numToRwx(group) + numToRwx(others);\n\t}\n\t\n\tfunction exportFileList() {\n\t\t// Simple CSV export of file list\n\t\tconst rows = Array.from(document.querySelectorAll('#fileTable tbody tr')).map(row => {\n\t\t\tconst cells = row.querySelectorAll('td');\n\t\t\tif (cells.length > 1) {\n\t\t\t\treturn {\n\t\t\t\t\tname: cells[1].textContent.trim(),\n\t\t\t\t\tsize: cells[2].textContent.trim(),\n\t\t\t\t\ttype: cells[3].textContent.trim(),\n\t\t\t\t\tmodified: cells[4].textContent.trim(),\n\t\t\t\t\tpermissions: cells[5].textContent.trim()\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn null;\n\t\t}).filter(row => row !== null);\n\t\t\n\t\tconst csvContent = \"data:text/csv;charset=utf-8,\" + \n\t\t\t\"Name,Size,Type,Modified,Permissions\\n\" +\n\t\t\trows.map(r => '\"' + r.name + '\",\"' + r.size + '\",\"' + r.type + '\",\"' + r.modified + '\",\"' + r.permissions + '\"').join(\"\\n\");\n\t\t\n\t\tconst encodedUri = encodeURI(csvContent);\n\t\tconst link = document.createElement(\"a\");\n\t\tlink.setAttribute(\"href\", encodedUri);\n\t\tlink.setAttribute(\"download\", \"files.csv\");\n\t\tdocument.body.appendChild(link);\n\t\tlink.click();\n\t\tdocument.body.removeChild(link);\n\t}\n\t\n\t// Handle file checkbox changes\n\tdocument.addEventListener('change', function(e) {\n\t\tif (e.target.classList.contains('file-checkbox')) {\n\t\t\tupdateDeleteSelectedButton();\n\t\t}\n\t});\n\t</script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
diff --git a/weed/server/filer_ui/filer.html b/weed/server/filer_ui/filer.html
index 935f7f808a..5653f41dd8 100644
--- a/weed/server/filer_ui/filer.html
+++ b/weed/server/filer_ui/filer.html
@@ -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);
+ uploadItems([...files].map(file => ({'file': file, 'path': file.webkitRelativePath || file.name})));
+ }
+
+ // 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();
- files.forEach(uploadFile);
+ uploadQueue.push(...items);
+ uploadNext();
}
- function startUpload(file, i) {
- uploadList[file.name] = {'name': file.name, 'percent': 0, 'finish': false};
+ 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) {