This is an automated email from the ASF dual-hosted git repository.

snoopdave pushed a commit to branch media-library
in repository https://gitbox.apache.org/repos/asf/roller.git

commit 232e99a2592416af18c4c50b7511629c81d4d85f
Author: David M. Johnson <[email protected]>
AuthorDate: Sun Oct 25 13:42:38 2026 -0400

    Media upload: one picker with drag and drop, per-file results, retry failed 
files
    
    The upload page has one multiple-file picker and a drop area. Chosen
    files go into a list with a preview, name, size and a remove button;
    the shared description, tags and copyright come after the files, and
    each file keeps its own name. The page shows the configured limits.
    
    With JavaScript the files go in one request and MediaFileAddResult.jsp
    answers with a result per file and a fresh salt, so a retry sends only
    the files that failed and never uploads a saved file twice. If the
    connection drops or the server fails after the files were sent, the
    outcome is reported as unknown, with a link to the folder, and nothing
    is retried. Without JavaScript the form posts as before.
    
    The server caps one upload at uploads.maxFilesPerRequest files (20).
---
 .../weblogger/ui/struts2/editor/MediaFileAdd.java  | 144 ++++++++-
 .../main/resources/ApplicationResources.properties |  25 +-
 .../roller/weblogger/config/roller.properties      |   4 +
 app/src/main/resources/struts.xml                  |   7 +-
 .../webapp/WEB-INF/jsps/editor/MediaFileAdd.jsp    | 152 +++++----
 .../WEB-INF/jsps/editor/MediaFileAddResult.jsp     |  21 ++
 .../main/webapp/roller-ui/scripts/media-upload.js  | 342 +++++++++++++++++++++
 app/src/main/webapp/roller-ui/styles/roller.css    | 138 +++++++++
 8 files changed, 768 insertions(+), 65 deletions(-)

diff --git 
a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MediaFileAdd.java
 
b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MediaFileAdd.java
index 07854b652..e8d2a4023 100644
--- 
a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MediaFileAdd.java
+++ 
b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MediaFileAdd.java
@@ -23,7 +23,12 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Iterator;
+import java.util.LinkedHashMap;
 import java.util.List;
+import java.util.Map;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
 
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.text.StringEscapeUtils;
@@ -32,6 +37,7 @@ import org.apache.commons.logging.LogFactory;
 import org.apache.roller.weblogger.WebloggerException;
 import org.apache.roller.weblogger.business.MediaFileManager;
 import org.apache.roller.weblogger.business.WebloggerFactory;
+import org.apache.roller.weblogger.config.WebloggerConfig;
 import org.apache.roller.weblogger.config.WebloggerRuntimeConfig;
 import org.apache.roller.weblogger.pojos.MediaFile;
 import org.apache.roller.weblogger.pojos.MediaFileDirectory;
@@ -70,6 +76,15 @@ public class MediaFileAdd extends MediaFileBase implements 
UploadedFilesAware {
 
     private String directoryName = null;
 
+    // "json" when the upload page sends the files with fetch() and wants the
+    // per-file results as JSON (MediaFileAddResult.jsp)
+    private String format = null;
+
+    // comma separated IDs of files just uploaded, for done()
+    private String uploadedIds = null;
+
+    static final String JSON = "json";
+
     public MediaFileAdd() {
         this.actionName = "mediaFileAdd";
         this.desiredMenu = "editor";
@@ -149,6 +164,13 @@ public class MediaFileAdd extends MediaFileBase implements 
UploadedFilesAware {
 
             MediaFileManager manager = 
WebloggerFactory.getWeblogger().getMediaFileManager();
 
+            long fileCount = uploadedFiles == null ? 0
+                    : uploadedFiles.stream().filter(u -> u != null).count();
+            if (fileCount > getMaxFiles()) {
+                addError("mediaFileAdd.tooManyFiles", 
Integer.toString(getMaxFiles()));
+                return result(INPUT);
+            }
+
             if (uploadedFiles != null && !uploadedFiles.isEmpty()) {
 
                 // loop over uploaded files and try saving each one; a file 
that
@@ -226,19 +248,56 @@ public class MediaFileAdd extends MediaFileBase 
implements UploadedFilesAware {
 
                 if (newImages.isEmpty() && newFiles.isEmpty()) {
                     // nothing was saved; the errors are on the upload form
-                    return INPUT;
+                    return result(INPUT);
                 }
 
                 // Files that were saved are listed on the success page, with
                 // any that failed, so a partial upload is never hidden.
                 this.pageTitle = "mediaFileAddSuccess.title";
-                return SUCCESS;
+                return result(SUCCESS);
 
             } else {
                 addError("error.upload.file");
             }
         }
-        return INPUT;
+        return result(INPUT);
+    }
+
+    private String result(String pageResult) {
+        return JSON.equals(format) ? JSON : pageResult;
+    }
+
+    /**
+     * Shows the success page for files already uploaded, after the upload page
+     * sent them with fetch(). Only files of this weblog are shown.
+     */
+    @SkipValidation
+    public String done() {
+        if (StringUtils.isNotBlank(uploadedIds)) {
+            MediaFileManager manager = 
WebloggerFactory.getWeblogger().getMediaFileManager();
+            for (String id : StringUtils.split(uploadedIds, ',')) {
+                try {
+                    MediaFile mediaFile = 
manager.getMediaFile(getActionWeblog(), id.trim());
+                    if (mediaFile == null) {
+                        continue;
+                    }
+                    if (mediaFile.isImageFile()) {
+                        newImages.add(mediaFile);
+                    } else {
+                        newFiles.add(mediaFile);
+                    }
+                    uploadResults.add(UploadResult.uploaded(mediaFile));
+                    bean.setDirectoryId(mediaFile.getDirectory().getId());
+                } catch (WebloggerException ex) {
+                    log.error("Error looking up uploaded media file " + id, 
ex);
+                }
+            }
+        }
+        if (newImages.isEmpty() && newFiles.isEmpty()) {
+            return INPUT;
+        }
+        this.pageTitle = "mediaFileAddSuccess.title";
+        return SUCCESS;
     }
 
     /**
@@ -322,6 +381,79 @@ public class MediaFileAdd extends MediaFileBase implements 
UploadedFilesAware {
         this.newFiles = newFiles;
     }
 
+    /**
+     * The upload outcome for the upload page's script: one entry per file,
+     * the form errors, and a fresh salt for a retry (salts are single-use).
+     */
+    public String getResultJson() {
+        List<Map<String, Object>> files = new ArrayList<>();
+        for (UploadResult r : uploadResults) {
+            Map<String, Object> file = new LinkedHashMap<>();
+            file.put("name", r.getFileName());
+            file.put("uploaded", r.isUploaded());
+            if (r.isUploaded()) {
+                file.put("id", r.getMediaFile().getId());
+                file.put("url", r.getMediaFile().getPermalink());
+            } else {
+                file.put("error", r.getErrorText());
+            }
+            files.add(file);
+        }
+        List<String> errors = new ArrayList<>();
+        if (uploadResults.isEmpty()) {
+            // errors for the whole upload: uploads off, too many files, no 
files
+            for (String error : getActionErrors()) {
+                
errors.add(StringEscapeUtils.unescapeHtml4(error.replaceAll("<[^>]*>", "")));
+            }
+        }
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("files", files);
+        result.put("errors", errors);
+        result.put("salt", getSalt());
+        try {
+            return new ObjectMapper().writeValueAsString(result);
+        } catch (JsonProcessingException e) {
+            throw new IllegalStateException(e);
+        }
+    }
+
+    /** Most files one upload may contain (uploads.maxFilesPerRequest). */
+    public int getMaxFiles() {
+        return Math.max(1, 
WebloggerConfig.getIntProperty("uploads.maxFilesPerRequest", 20));
+    }
+
+    public boolean isUploadsEnabled() {
+        return WebloggerRuntimeConfig.getBooleanProperty("uploads.enabled");
+    }
+
+    /** Largest file allowed, in MB, as configured. */
+    public String getMaxFileMB() {
+        return WebloggerRuntimeConfig.getProperty("uploads.file.maxsize");
+    }
+
+    /** Largest total for all of a weblog's files, in MB, as configured. */
+    public String getMaxDirMB() {
+        return WebloggerRuntimeConfig.getProperty("uploads.dir.maxsize");
+    }
+
+    public String getFormat() {
+        return format;
+    }
+
+    @StrutsParameter
+    public void setFormat(String format) {
+        this.format = format;
+    }
+
+    public String getUploadedIds() {
+        return uploadedIds;
+    }
+
+    @StrutsParameter
+    public void setUploadedIds(String uploadedIds) {
+        this.uploadedIds = uploadedIds;
+    }
+
     public List<UploadResult> getUploadResults() {
         return uploadResults;
     }
@@ -380,6 +512,12 @@ public class MediaFileAdd extends MediaFileBase implements 
UploadedFilesAware {
             return error;
         }
 
+        /** Why the file failed, as plain text; null if it was saved. */
+        public String getErrorText() {
+            return error == null ? null
+                    : 
StringEscapeUtils.unescapeHtml4(error.replaceAll("<[^>]*>", ""));
+        }
+
         public boolean isUploaded() {
             return mediaFile != null;
         }
diff --git a/app/src/main/resources/ApplicationResources.properties 
b/app/src/main/resources/ApplicationResources.properties
index ad8c505c8..4e089ead8 100644
--- a/app/src/main/resources/ApplicationResources.properties
+++ b/app/src/main/resources/ApplicationResources.properties
@@ -774,14 +774,35 @@ mediaFileImageChooser.pageTip=Select an image and it will 
be included as a thumb
 
 # -- Media File Add
 
-mediaFileAdd.title=Add new media file
-mediaFileAdd.pageTip=Use this page to upload up to five new media files. Each 
file keeps its own name. The description, tags and other properties are applied 
to all files uploaded.
+mediaFileAdd.title=Upload files
 mediaFileAdd.fileLocation=Choose media files to upload
 mediaFileAdd.tags=Tags (space separated)
 mediaFileAdd.copyright=Copyright statement
 mediaFileAdd.directory=Folder
 mediaFileAdd.includeGallery=Include in Gallery?
 mediaFileAdd.upload=Upload
+mediaFileAdd.folder=Upload to folder
+mediaFileAdd.dropHere=Drag files here, or choose them
+mediaFileAdd.limits=Up to {0} files at a time, each up to {1} MB. All files in 
this weblog together may use up to {2} MB.
+mediaFileAdd.fileListLabel=Files to upload
+mediaFileAdd.shared=Apply to these files (optional)
+mediaFileAdd.sharedHelp=Each file keeps its own name. You can rename a file on 
its details page after upload.
+mediaFileAdd.uploadsDisabled=File uploads are turned off for this site. A site 
administrator can turn them on in Server Administration.
+mediaFileAdd.tooManyFiles=You can upload up to {0} files at a time.
+mediaFileAdd.remove=Remove {0}
+mediaFileAdd.selectedCount={0} file(s) ready to upload
+mediaFileAdd.statusQueued=Ready
+mediaFileAdd.statusUploading=Uploading
+mediaFileAdd.statusUploaded=Uploaded
+mediaFileAdd.statusFailed=Failed
+mediaFileAdd.statusUnknown=Outcome unknown
+mediaFileAdd.tooLarge=Larger than {0} MB
+mediaFileAdd.uploading=Uploading {0} file(s). Keep this page open.
+mediaFileAdd.someFailed={0} uploaded, {1} failed. Retry the failed files, or 
remove them from the list.
+mediaFileAdd.retry=Retry failed files
+mediaFileAdd.continue=Continue with the uploaded files
+mediaFileAdd.unknownOutcome=The connection was lost after the files were sent, 
so some of them may have been saved. Check the folder before you upload them 
again.
+mediaFileAdd.serverError=The server could not process the upload ({0}).
 mediaFileAdd.multipleNames=(Multiple names)
 mediaFileAdd.errorUploading=Error uploading file {0}
 
diff --git 
a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties 
b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties
index 645e0f9d1..5a758a879 100644
--- 
a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties
+++ 
b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties
@@ -119,6 +119,10 @@ mediafile.resource.url=/resources
 # Migrate old file resources to Roller 5.0 Mediafile Storage automatically
 uploads.migrate.auto=false
 
+# Most files one media upload may contain. The file size and weblog quota
+# limits are runtime settings on the Server Administration page.
+uploads.maxFilesPerRequest=20
+
 # Directory in which search index is to be created 
 # (delete this directory to force Roller to recreate the entire search index)
 search.index.dir=${user.home}/roller_data/search-index
diff --git a/app/src/main/resources/struts.xml 
b/app/src/main/resources/struts.xml
index e9713be15..80dfbb179 100644
--- a/app/src/main/resources/struts.xml
+++ b/app/src/main/resources/struts.xml
@@ -326,11 +326,8 @@
             <result name="input" type="tiles">.MediaFileAdd</result>
             <result name="success" type="tiles">.MediaFileAddSuccess</result>
             <result name="error" type="tiles">.MediaFileAdd</result>
-            <result name="cancel" type="redirectAction">
-                <param name="actionName">mediaFileView</param>
-                <param name="weblog">${weblog}</param>
-            </result>
-            <allowed-methods>execute,save</allowed-methods>
+            <result name="json" 
type="dispatcher">/WEB-INF/jsps/editor/MediaFileAddResult.jsp</result>
+            <allowed-methods>execute,save,done</allowed-methods>
         </action>
 
         <action name="mediaFileEdit"
diff --git a/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileAdd.jsp 
b/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileAdd.jsp
index 6ed5ad3e0..87a909044 100644
--- a/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileAdd.jsp
+++ b/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileAdd.jsp
@@ -17,74 +17,116 @@
 --%>
 <%@ include file="/WEB-INF/jsps/taglibs-struts2.jsp" %>
 
-
-<p class="subtitle"> <s:text name="mediaFileAdd.title"/> </p>
-<p class="pagetip"> <s:text name="mediaFileAdd.pageTip"/> </p>
-
-<s:form id="entry" action="mediaFileAdd!save"
-        method="POST" enctype="multipart/form-data" theme="bootstrap" 
cssClass="form-horizontal">
+<%-- Upload media files. One file picker (or drag and drop) fills a list; the 
shared metadata
+     comes after it. With JavaScript (media-upload.js) the files go in one 
request whose per-file
+     results come back as JSON, so failed files can be retried alone. Without 
it, the form posts
+     normally and the success page lists the results. --%>
+
+<s:url var="mediaFileViewURL" escapeAmp="false" action="mediaFileView">
+    <s:param name="weblog" value="%{actionWeblog.handle}"/>
+    <s:param name="directoryName" value="%{directoryName}"/>
+</s:url>
+
+<p class="media-back">
+    <a href="<s:property value='%{mediaFileViewURL}'/>">
+        <span class="bi bi-arrow-left" aria-hidden="true"></span>
+        <s:text name="mediaFileEdit.backToLibrary"/></a>
+</p>
+
+<s:if test="!uploadsEnabled">
+    <div class="alert alert-warning"><s:text 
name="mediaFileAdd.uploadsDisabled"/></div>
+</s:if>
+<s:else>
+
+<s:url var="doneURL" escapeAmp="false" action="mediaFileAdd!done">
+    <s:param name="weblog" value="%{actionWeblog.handle}"/>
+</s:url>
+<s:url var="folderNewestURL" escapeAmp="false" action="mediaFileView">
+    <s:param name="weblog" value="%{actionWeblog.handle}"/>
+</s:url>
+
+<s:form id="uploadForm" action="mediaFileAdd!save" method="POST" 
enctype="multipart/form-data"
+        theme="simple" cssClass="media-upload">
     <s:hidden name="salt"/>
     <s:hidden name="weblog"/>
     <s:hidden name="directoryName"/>
 
-    <s:textarea name="bean.description"  rows="3" 
label="%{getText('generic.description')}"/>
+    <div id="mediaUpload" hidden
+         data-max-files="<s:property value='maxFiles'/>"
+         data-max-file-mb="<s:property value='maxFileMB'/>"
+         data-done-url="<s:property value='%{doneURL}'/>"
+         data-folder-url="<s:property value='%{folderNewestURL}'/>"
+         data-status-queued="<s:text name='mediaFileAdd.statusQueued'/>"
+         data-status-uploading="<s:text name='mediaFileAdd.statusUploading'/>"
+         data-status-uploaded="<s:text name='mediaFileAdd.statusUploaded'/>"
+         data-status-failed="<s:text name='mediaFileAdd.statusFailed'/>"
+         data-status-unknown="<s:text name='mediaFileAdd.statusUnknown'/>"
+         data-too-large="<s:text name='mediaFileAdd.tooLarge'/>"
+         data-too-many="<s:text name='mediaFileAdd.tooManyFiles'/>"
+         data-remove="<s:text name='mediaFileAdd.remove'/>"
+         data-selected-count="<s:text name='mediaFileAdd.selectedCount'/>"
+         data-uploading="<s:text name='mediaFileAdd.uploading'/>"
+         data-some-failed="<s:text name='mediaFileAdd.someFailed'/>"
+         data-retry="<s:text name='mediaFileAdd.retry'/>"
+         data-unknown-outcome="<s:text name='mediaFileAdd.unknownOutcome'/>"
+         data-server-error="<s:text name='mediaFileAdd.serverError'/>"></div>
+
+    <div class="media-upload-folder">
+        <label class="form-label" for="uploadFolder"><s:text 
name="mediaFileAdd.folder"/></label>
+        <s:select id="uploadFolder" name="bean.directoryId" 
list="allDirectories" listKey="id" listValue="name"
+                  cssClass="form-select"/>
+    </div>
 
-    <s:textarea name="bean.copyrightText" rows="3" 
label="%{getText('mediaFileAdd.copyright')}"/>
+    <div id="dropZone" class="media-drop-zone">
+        <span class="bi bi-cloud-arrow-up" aria-hidden="true"></span>
+        <label class="form-label" for="fileInput"><s:text 
name="mediaFileAdd.dropHere"/></label>
+        <input type="file" id="fileInput" name="uploadedFiles" multiple 
class="form-control"
+               aria-describedby="uploadLimits"/>
+        <p class="form-text" id="uploadLimits">
+            <s:text name="mediaFileAdd.limits">
+                <s:param value="maxFiles"/>
+                <s:param value="maxFileMB"/>
+                <s:param value="maxDirMB"/>
+            </s:text>
+        </p>
+    </div>
 
-    <s:textfield name="bean.tagsAsString" maxlength="255" 
label="%{getText('mediaFileAdd.tags')}"/>
+    <ul id="fileList" class="media-upload-list" aria-label="<s:text 
name='mediaFileAdd.fileListLabel'/>"></ul>
 
-    <s:select name="bean.directoryId" list="allDirectories"
-              listKey="id" listValue="name" 
label="%{getText('mediaFileAdd.directory')}"/>
+    <details class="media-upload-shared">
+        <summary><s:text name="mediaFileAdd.shared"/></summary>
+        <p class="form-text"><s:text name="mediaFileAdd.sharedHelp"/></p>
 
-    <s:checkbox name="bean.sharedForGallery"
-                label="%{getText('mediaFileAdd.includeGallery')}"
-                tooltip="%{getText('mediaFileEdit.includeGalleryHelp')}"/>
+        <label class="form-label" for="uploadDescription"><s:text 
name="generic.description"/></label>
+        <s:textarea id="uploadDescription" name="bean.description" rows="2" 
cssClass="form-control"/>
 
-    <div class="card">
-        <div class="card-header">
-            <h4 class="card-title">
-                <s:text name="mediaFileAdd.fileLocation"/>
-            </h4>
-        </div>
-        <div class="card-body">
-            <s:file id="fileControl0" name="uploadedFiles" size="30" 
cssClass="form-control mb-2" />
-            <s:file id="fileControl1" name="uploadedFiles" size="30" 
cssClass="form-control mb-2" />
-            <s:file id="fileControl2" name="uploadedFiles" size="30" 
cssClass="form-control mb-2" />
-            <s:file id="fileControl3" name="uploadedFiles" size="30" 
cssClass="form-control mb-2" />
-            <s:file id="fileControl4" name="uploadedFiles" size="30" 
cssClass="form-control mb-2" />
-        </div>
-    </div>
+        <label class="form-label" for="uploadTags"><s:text 
name="mediaFileAdd.tags"/></label>
+        <s:textfield id="uploadTags" name="bean.tagsAsString" maxlength="255" 
cssClass="form-control"/>
+
+        <label class="form-label" for="uploadCopyright"><s:text 
name="mediaFileAdd.copyright"/></label>
+        <s:textarea id="uploadCopyright" name="bean.copyrightText" rows="2" 
cssClass="form-control"/>
 
-    <div class="row mb-3">
-        <div class="col-sm-9 offset-sm-3">
-            <s:submit id="uploadButton" cssClass="btn btn-primary" 
theme="simple"
-                      value="%{getText('mediaFileAdd.upload')}" 
action="mediaFileAdd!save"/>
-            <s:url var="mediaFileViewURL" escapeAmp="false" 
action="mediaFileView">
-                <s:param name="weblog" value="%{actionWeblog.handle}"/>
-                <s:param name="directoryName" value="%{directoryName}"/>
-            </s:url>
-            <a class="btn btn-outline-secondary" href="<s:property 
value='%{mediaFileViewURL}'/>">
-                <s:text name="generic.cancel"/></a>
+        <div class="form-check">
+            <s:checkbox id="uploadGallery" name="bean.sharedForGallery" 
cssClass="form-check-input"/>
+            <label class="form-check-label" for="uploadGallery"><s:text 
name="mediaFileAdd.includeGallery"/></label>
+            <p class="form-text"><s:text 
name="mediaFileEdit.includeGalleryHelp"/></p>
         </div>
+    </details>
+
+    <div class="media-upload-buttons">
+        <button type="submit" id="uploadButton" class="btn btn-primary">
+            <span class="bi bi-upload" aria-hidden="true"></span>
+            <span id="uploadButtonLabel"><s:text 
name="mediaFileAdd.upload"/></span></button>
+        <a class="btn btn-outline-secondary" href="<s:property 
value='%{mediaFileViewURL}'/>">
+            <s:text name="generic.cancel"/></a>
+        <a class="btn btn-outline-success" id="continueLink" hidden href="#">
+            <s:text name="mediaFileAdd.continue"/></a>
     </div>
 
-</s:form>
-
-
-<%-- ================================================================== --%>
+    <div id="uploadStatus" class="media-upload-status" role="status" 
aria-live="polite"></div>
 
-<script>
+</s:form>
 
-    // Upload is enabled once a file is chosen. Each file keeps its own name.
-    $(document).ready(function () {
-        var uploadButton = $("#uploadButton");
-        uploadButton.attr("disabled", true);
-        $("input[type='file']").change(function () {
-            var chosen = $("input[type='file']").filter(function () {
-                return this.value.length > 0;
-            }).length;
-            uploadButton.attr("disabled", chosen === 0);
-        });
-    });
+<script src="<s:url value='/roller-ui/scripts/media-upload.js'/>"></script>
 
-</script>
+</s:else>
diff --git a/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileAddResult.jsp 
b/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileAddResult.jsp
new file mode 100644
index 000000000..90063e9a9
--- /dev/null
+++ b/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileAddResult.jsp
@@ -0,0 +1,21 @@
+<%--
+  Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  The ASF licenses this file to You
+  under the Apache License, Version 2.0 (the "License"); you may not
+  use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.  For additional information regarding
+  copyright in this work, please see the NOTICE file in the top level
+  directory of this distribution.
+--%>
+<%@ page contentType="application/json; charset=UTF-8" 
trimDirectiveWhitespaces="true" %>
+<%@ taglib uri="/struts-tags" prefix="s" %>
+<%-- Upload outcome for MediaFileAdd.jsp's script; 
MediaFileAdd.getResultJson() writes it with Jackson --%>
+<s:property value="resultJson" escapeHtml="false"/>
diff --git a/app/src/main/webapp/roller-ui/scripts/media-upload.js 
b/app/src/main/webapp/roller-ui/scripts/media-upload.js
new file mode 100644
index 000000000..5260b9916
--- /dev/null
+++ b/app/src/main/webapp/roller-ui/scripts/media-upload.js
@@ -0,0 +1,342 @@
+/*
+* Licensed to the Apache Software Foundation (ASF) under one or more
+*  contributor license agreements.  The ASF licenses this file to You
+* under the Apache License, Version 2.0 (the "License"); you may not
+* use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.  For additional information regarding
+* copyright in this work, please see the NOTICE file in the top level
+* directory of this distribution.
+*/
+
+/*
+ * Upload page (MediaFileAdd.jsp). Chosen or dropped files go into a list; 
Upload
+ * sends the files that are not yet uploaded in one request with format=json, 
and
+ * MediaFileAddResult.jsp answers with a result per file and a fresh salt. 
Failed
+ * files stay in the list for a retry; uploaded files are never sent again. If 
the
+ * connection drops after sending, the outcome is unknown and nothing is 
retried
+ * automatically. Localized strings come from data-* attributes on 
#mediaUpload;
+ * file names are only written with text APIs.
+ */
+(function () {
+    var config = document.getElementById("mediaUpload");
+    var form = document.getElementById("uploadForm");
+    if (!config || !form || !window.fetch || !window.FormData) {
+        return; // the form posts normally
+    }
+
+    var input = document.getElementById("fileInput");
+    var dropZone = document.getElementById("dropZone");
+    var list = document.getElementById("fileList");
+    var button = document.getElementById("uploadButton");
+    var buttonLabel = document.getElementById("uploadButtonLabel");
+    var status = document.getElementById("uploadStatus");
+    var continueLink = document.getElementById("continueLink");
+    var folder = document.getElementById("uploadFolder");
+    var uploadLabel = buttonLabel.textContent;
+
+    var maxFiles = parseInt(config.getAttribute("data-max-files"), 10) || 20;
+    var maxFileMB = parseFloat(config.getAttribute("data-max-file-mb")) || 0;
+
+    // entries: {file, state: queued|uploading|uploaded|failed|unknown, error, 
item}
+    var entries = [];
+    var uploadedIds = [];
+    var busy = false;
+
+    function text(name) {
+        return config.getAttribute("data-" + name) || "";
+    }
+
+    function format(message) {
+        var args = Array.prototype.slice.call(arguments, 1);
+        return message.replace(/\{(\d)\}/g, function (match, i) {
+            return args[i] !== undefined ? args[i] : match;
+        });
+    }
+
+    function formatSize(bytes) {
+        if (bytes < 1024) {
+            return bytes + " bytes";
+        }
+        var units = ["KB", "MB", "GB"];
+        var value = bytes;
+        var unit = -1;
+        do {
+            value /= 1024;
+            unit++;
+        } while (value >= 1024 && unit < units.length - 1);
+        return (value < 10 ? Math.round(value * 10) / 10 : Math.round(value)) 
+ " " + units[unit];
+    }
+
+    function tooLarge(file) {
+        return maxFileMB > 0 && file.size > maxFileMB * 1024 * 1024;
+    }
+
+    function pending() {
+        return entries.filter(function (e) {
+            return e.state === "queued" || e.state === "failed";
+        });
+    }
+
+    // ----- the file list ----------------------------------------------------
+
+    function addFiles(files) {
+        Array.prototype.forEach.call(files, function (file) {
+            var duplicate = entries.some(function (e) {
+                return e.state !== "uploaded" && e.file.name === file.name
+                    && e.file.size === file.size && e.file.lastModified === 
file.lastModified;
+            });
+            if (!duplicate) {
+                var entry = {file: file, state: "queued", error: null};
+                if (tooLarge(file)) {
+                    entry.state = "failed";
+                    entry.error = format(text("too-large"), maxFileMB);
+                }
+                entries.push(entry);
+                entry.item = renderEntry(entry);
+                list.appendChild(entry.item);
+            }
+        });
+        input.value = "";
+        update();
+    }
+
+    function renderEntry(entry) {
+        var item = document.createElement("li");
+        item.className = "media-upload-item";
+
+        var preview = document.createElement("span");
+        preview.className = "media-upload-preview";
+        if (/^image\//.test(entry.file.type) && entry.file.size < 20 * 1024 * 
1024) {
+            var img = document.createElement("img");
+            img.alt = "";
+            img.src = URL.createObjectURL(entry.file);
+            img.onload = function () {
+                URL.revokeObjectURL(img.src);
+            };
+            preview.appendChild(img);
+        } else {
+            var icon = document.createElement("span");
+            icon.className = "bi bi-file-earmark";
+            icon.setAttribute("aria-hidden", "true");
+            preview.appendChild(icon);
+        }
+
+        var name = document.createElement("span");
+        name.className = "media-upload-name";
+        name.textContent = entry.file.name;
+
+        var size = document.createElement("span");
+        size.className = "media-upload-size";
+        size.textContent = formatSize(entry.file.size);
+
+        var state = document.createElement("span");
+        state.className = "media-upload-state";
+
+        var remove = document.createElement("button");
+        remove.type = "button";
+        remove.className = "btn btn-sm btn-outline-secondary 
media-upload-remove";
+        remove.setAttribute("aria-label", format(text("remove"), 
entry.file.name));
+        remove.innerHTML = '<span class="bi bi-x-lg" 
aria-hidden="true"></span>';
+        remove.addEventListener("click", function () {
+            entries.splice(entries.indexOf(entry), 1);
+            item.remove();
+            update();
+            input.focus();
+        });
+
+        item.appendChild(preview);
+        item.appendChild(name);
+        item.appendChild(size);
+        item.appendChild(state);
+        item.appendChild(remove);
+        return item;
+    }
+
+    function update() {
+        entries.forEach(function (entry) {
+            var state = entry.item.querySelector(".media-upload-state");
+            var label = text("status-" + entry.state);
+            state.textContent = entry.error ? label + ": " + entry.error : 
label;
+            entry.item.setAttribute("data-state", entry.state);
+            entry.item.querySelector(".media-upload-remove").hidden =
+                busy || entry.state === "uploaded" || entry.state === 
"uploading";
+        });
+
+        var sendable = pending().filter(function (e) {
+            return !tooLarge(e.file);
+        });
+        var anyFailed = entries.some(function (e) {
+            return e.state === "failed";
+        });
+        var anyUploaded = uploadedIds.length > 0;
+
+        button.disabled = busy || sendable.length === 0 || sendable.length > 
maxFiles;
+        buttonLabel.textContent = anyUploaded && anyFailed ? text("retry") : 
uploadLabel;
+
+        continueLink.hidden = busy || !anyUploaded;
+        continueLink.href = config.getAttribute("data-done-url")
+            + "&uploadedIds=" + encodeURIComponent(uploadedIds.join(","));
+
+        if (!busy && !anyUploaded) {
+            status.textContent = sendable.length > maxFiles
+                ? format(text("too-many"), maxFiles)
+                : (sendable.length > 0 ? format(text("selected-count"), 
sendable.length) : "");
+        }
+    }
+
+    input.addEventListener("change", function () {
+        addFiles(input.files);
+    });
+
+    ["dragenter", "dragover"].forEach(function (type) {
+        dropZone.addEventListener(type, function (e) {
+            e.preventDefault();
+            dropZone.classList.add("dragging");
+        });
+    });
+    ["dragleave", "drop"].forEach(function (type) {
+        dropZone.addEventListener(type, function (e) {
+            e.preventDefault();
+            dropZone.classList.remove("dragging");
+        });
+    });
+    dropZone.addEventListener("drop", function (e) {
+        if (e.dataTransfer && e.dataTransfer.files.length) {
+            addFiles(e.dataTransfer.files);
+        }
+    });
+
+    // ----- sending ----------------------------------------------------------
+
+    function folderLink() {
+        return config.getAttribute("data-folder-url") + "&directoryId="
+            + encodeURIComponent(folder.value);
+    }
+
+    function showStatus(message, linkText, linkHref) {
+        status.textContent = message;
+        if (linkText) {
+            var link = document.createElement("a");
+            link.href = linkHref;
+            link.textContent = linkText;
+            status.appendChild(document.createTextNode(" "));
+            status.appendChild(link);
+        }
+    }
+
+    form.addEventListener("submit", function (e) {
+        e.preventDefault();
+        var sending = pending().filter(function (entry) {
+            return !tooLarge(entry.file);
+        });
+        if (busy || sending.length === 0 || sending.length > maxFiles) {
+            return;
+        }
+
+        var data = new FormData();
+        Array.prototype.forEach.call(form.elements, function (field) {
+            if (!field.name || field.type === "file" || field.type === 
"submit" || field.disabled) {
+                return;
+            }
+            if ((field.type === "checkbox" || field.type === "radio") && 
!field.checked) {
+                return;
+            }
+            data.append(field.name, field.value);
+        });
+        data.append("format", "json");
+        sending.forEach(function (entry) {
+            entry.state = "uploading";
+            entry.error = null;
+            data.append("uploadedFiles", entry.file, entry.file.name);
+        });
+
+        busy = true;
+        update();
+        status.textContent = format(text("uploading"), sending.length);
+
+        fetch(form.action, {method: "POST", body: data, credentials: 
"same-origin"})
+            .then(function (response) {
+                var type = response.headers.get("Content-Type") || "";
+                if (response.status >= 500) {
+                    // the server may have saved files before it failed
+                    throw {unknown: true};
+                }
+                if (!response.ok || type.indexOf("json") === -1) {
+                    // refused before saving: too large, bad salt, session 
expired
+                    throw {server: String(response.status)};
+                }
+                return response.json();
+            })
+            .then(function (result) {
+                if (result.salt) {
+                    form.querySelector("input[name='salt']").value = 
result.salt;
+                }
+                // match results to the files sent, by name, in order
+                result.files.forEach(function (r) {
+                    var entry = sending.filter(function (s) {
+                        return s.state === "uploading" && s.file.name === 
r.name;
+                    })[0];
+                    if (!entry) {
+                        return;
+                    }
+                    if (r.uploaded) {
+                        entry.state = "uploaded";
+                        uploadedIds.push(r.id);
+                    } else {
+                        entry.state = "failed";
+                        entry.error = r.error;
+                    }
+                });
+                var formError = (result.errors || []).join(" ");
+                sending.forEach(function (entry) {
+                    if (entry.state === "uploading") {
+                        entry.state = "failed";
+                        entry.error = formError || null;
+                    }
+                });
+                busy = false;
+                update();
+
+                var failed = entries.filter(function (e) {
+                    return e.state === "failed";
+                }).length;
+                if (failed === 0 && uploadedIds.length > 0) {
+                    window.location.href = continueLink.href;
+                } else if (uploadedIds.length > 0) {
+                    showStatus(format(text("some-failed"), uploadedIds.length, 
failed));
+                } else {
+                    showStatus(formError || format(text("some-failed"), 0, 
failed));
+                }
+            })
+            .catch(function (error) {
+                busy = false;
+                if (error && error.server) {
+                    // the server refused the request, so nothing was saved
+                    sending.forEach(function (entry) {
+                        entry.state = "failed";
+                        entry.error = null;
+                    });
+                    update();
+                    showStatus(format(text("server-error"), error.server));
+                } else {
+                    // the request may or may not have reached the server
+                    sending.forEach(function (entry) {
+                        entry.state = "unknown";
+                    });
+                    update();
+                    showStatus(text("unknown-outcome"), 
folder.options[folder.selectedIndex].text,
+                        folderLink());
+                }
+            });
+    });
+
+    update();
+})();
diff --git a/app/src/main/webapp/roller-ui/styles/roller.css 
b/app/src/main/webapp/roller-ui/styles/roller.css
index 21409df17..0dc6d0834 100644
--- a/app/src/main/webapp/roller-ui/styles/roller.css
+++ b/app/src/main/webapp/roller-ui/styles/roller.css
@@ -783,6 +783,144 @@ body {
     }
 }
 
+/* media upload (MediaFileAdd.jsp) */
+
+.media-upload > fieldset > * + * {
+    margin-top: 1rem;
+}
+
+.media-upload-folder .form-select {
+    max-width: 20rem;
+}
+
+.media-drop-zone {
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    gap: 0.5rem;
+    padding: 2rem 1rem;
+    border: 2px dashed var(--bs-border-color);
+    border-radius: var(--bs-border-radius-lg);
+    background-color: var(--bs-tertiary-bg);
+    text-align: center;
+}
+
+.media-drop-zone.dragging {
+    border-color: var(--bs-primary);
+    background-color: var(--bs-primary-bg-subtle);
+}
+
+.media-drop-zone > .bi {
+    font-size: 2.5rem;
+    color: var(--bs-secondary-color);
+}
+
+.media-drop-zone .form-control {
+    max-width: 28rem;
+}
+
+.media-upload-list {
+    list-style: none;
+    padding: 0;
+    margin: 0;
+}
+
+.media-upload-list:empty {
+    display: none;
+}
+
+.media-upload-item {
+    display: grid;
+    grid-template-columns: 3rem minmax(0, 1fr) auto auto;
+    grid-template-areas: "preview name size remove" "preview state state 
remove";
+    align-items: center;
+    gap: 0 0.75rem;
+    padding: 0.5rem;
+    border-bottom: 1px solid var(--bs-border-color);
+}
+
+.media-upload-preview {
+    grid-area: preview;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    width: 3rem;
+    height: 3rem;
+    background-color: var(--bs-tertiary-bg);
+    border-radius: var(--bs-border-radius-sm);
+}
+
+.media-upload-preview img {
+    max-width: 100%;
+    max-height: 100%;
+    object-fit: contain;
+}
+
+.media-upload-preview .bi {
+    font-size: 1.5rem;
+    color: var(--bs-secondary-color);
+}
+
+.media-upload-name {
+    grid-area: name;
+    overflow-wrap: anywhere;
+}
+
+.media-upload-size {
+    grid-area: size;
+    font-size: 0.875rem;
+    color: var(--bs-secondary-color);
+}
+
+.media-upload-state {
+    grid-area: state;
+    font-size: 0.875rem;
+    color: var(--bs-secondary-color);
+}
+
+.media-upload-remove {
+    grid-area: remove;
+}
+
+.media-upload-item[data-state="uploaded"] .media-upload-state {
+    color: var(--bs-success-text-emphasis);
+}
+
+.media-upload-item[data-state="failed"] .media-upload-state,
+.media-upload-item[data-state="unknown"] .media-upload-state {
+    color: var(--bs-danger-text-emphasis);
+}
+
+.media-upload-shared summary {
+    cursor: pointer;
+    font-weight: 600;
+}
+
+.media-upload-shared .form-label {
+    margin-top: 0.75rem;
+}
+
+.media-upload-buttons {
+    display: flex;
+    flex-wrap: wrap;
+    gap: 0.5rem;
+}
+
+.media-upload-status:empty {
+    display: none;
+}
+
+.media-upload-failed {
+    list-style: none;
+    padding: 0;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+    .media-drop-zone {
+        transition: border-color 0.15s, background-color 0.15s;
+    }
+}
+
 /* Narrow screens (media pages set a device-width viewport): the folder list
    gives way to the folder picker in the page header */
 .media-folder-picker {

Reply via email to