Procházet zdrojové kódy

统一富文本上传限制并修复首页视频播放

新增 sys.uploadAjax 后端上传服务,统一校验图片、视频和普通文件大小;图片单张限制 20M,视频单个限制 1G,普通文件限制 10M,并保留图片压缩处理。

更新 CKEditor 上传适配器和 UEditor 配置,确保图片、视频、多图和粘贴上传入口都先按原文件大小校验,再通过同一上传接口处理。

修复多彩华夏视频弹窗在本地预览时无法播放的问题:从文章正文提取 video/source 链接时归一为当前站点 /web/upload 地址,并为无 fetch 的浏览器环境增加 XHR 兜底。

Validation:

- node --check WebRoot/apps/space/js/space.vue.subassembly.js

- node --check WebRoot/apps/space/plug-in/ckeditor5/src/plugins/upload/src/myUploadAdapter.js

- node --check WebRoot/main/ffkj-portal/portal-zq.js

- javac -encoding UTF-8 -cp WebRoot/WEB-INF/classes:WebRoot/WEB-INF/lib/* -d WebRoot/WEB-INF/classes src/space/core/apps/sys/service/UploadService.java

- Node 边界测试:图片 20M 通过、20M+1 拦截;视频 1G 通过、1G+1 拦截

- 浏览器复测:首页多彩华夏视频弹窗生成当前站点 mp4,readyState=4,error=null
非繁 před 5 měsíci
rodič
revize
b5dc8f9952

+ 28 - 7
WebRoot/apps/space/js/space.vue.subassembly.js

@@ -379,7 +379,7 @@ Vue.component('spaceEditor', {
 			// 编辑器需要的 js 文件
 			jsUrl: [
 				'/apps/space/plug-in/ckeditor5/build/ckeditor.js',
-				'/apps/space/plug-in/ckeditor5/src/plugins/upload/src/myUploadAdapter.js?v=2026062706'
+				'/apps/space/plug-in/ckeditor5/src/plugins/upload/src/myUploadAdapter.js?v=2026062712'
 			],
 			// 标识,全部为 true 则代表全部加载完成
 			jsUrlFlag: [],
@@ -513,7 +513,10 @@ Vue.component('spaceEditor', {
 		getUploadOptions: function () {
 			return {
 				imageQuality: this.imageQuality,
-				imageMaxWidth: 1920
+				imageMaxWidth: 1920,
+				imageMaxSize: 20 * 1024 * 1024,
+				videoMaxSize: 1024 * 1024 * 1024,
+				fileMaxSize: 10 * 1024 * 1024
 			};
 		},
 		myCustomUploadAdapterPlugin: function (editor) {
@@ -838,6 +841,27 @@ Vue.component('spaceEditor', {
 			this.editor.model.insertContent(modelFragment);
 			this.$emit("input", this.editor.getData());
 		},
+		escapeHtmlAttr: function (value) {
+			return String(value || "").replace(/[&<>"']/g, function (text) {
+				return {
+					"&": "&amp;",
+					"<": "&lt;",
+					">": "&gt;",
+					"\"": "&quot;",
+					"'": "&#39;"
+				}[text];
+			});
+		},
+		normalizeLocalUploadUrl: function (url) {
+			var text = String(url || "").trim().replace(/\\/g, "/");
+			var match = text.match(/^(?:https?:)?\/\/[^/]*(\/web\/upload\/.*)$/i);
+			if (match) {
+				text = match[1];
+			}
+			text = text.replace(/^(https?:)\/+(\/web\/upload\/.*)$/i, "$2");
+			text = text.replace(/(\/web\/upload\/modules)\/+/i, "$1/");
+			return text;
+		},
 		openVideoPicker: function () {
 			if (this.$refs.videoInput) {
 				this.$refs.videoInput.click();
@@ -866,11 +890,8 @@ Vue.component('spaceEditor', {
 					_this.uploadStatus = "正在上传视频 " + Math.round(loaded * 100 / total) + "%";
 				}
 			}).then(function (res) {
-				if (_this.editor && _this.editor.commands.get('mediaEmbed')) {
-					_this.editor.execute('mediaEmbed', res.default);
-				} else {
-					_this.insertHtml('<p><video controls playsinline preload="metadata" src="' + res.default + '"></video></p>');
-				}
+				var videoUrl = _this.normalizeLocalUploadUrl(res.default);
+				_this.insertHtml('<p><video controls playsinline preload="metadata" src="' + _this.escapeHtmlAttr(videoUrl) + '" style="max-width:100%;"></video></p>');
 				_this.$emit("input", _this.editor.getData());
 				space.message.success("视频已插入正文");
 			}).catch(function (msg) {

+ 56 - 5
WebRoot/apps/space/plug-in/ckeditor5/src/plugins/upload/src/myUploadAdapter.js

@@ -9,6 +9,7 @@ class MyUploadAdapter {
 	// Starts the upload process.
 	upload() {
 		return this.loader.file
+			.then(file => this._validateFileSize(file))
 			.then(file => this._prepareFile(file))
 			.then(file => new Promise((resolve, reject) => {
 				this._initRequest();
@@ -18,11 +19,13 @@ class MyUploadAdapter {
 	}
 
 	uploadPlainFile(file, onProgress) {
-		return this._prepareFile(file).then(uploadFile => new Promise((resolve, reject) => {
-			this._initRequest();
-			this._initListeners(resolve, reject, uploadFile, onProgress);
-			this._sendRequest(uploadFile);
-		}));
+		return this._validateFileSize(file)
+			.then(validFile => this._prepareFile(validFile))
+			.then(uploadFile => new Promise((resolve, reject) => {
+				this._initRequest();
+				this._initListeners(resolve, reject, uploadFile, onProgress);
+				this._sendRequest(uploadFile);
+			}));
 	}
 
 	// Aborts the upload process.
@@ -104,6 +107,19 @@ class MyUploadAdapter {
 		return this._compressImage(file).catch(() => file);
 	}
 
+	_validateFileSize(file) {
+		if (!file) {
+			return Promise.resolve(file);
+		}
+
+		var maxSize = this._getMaxSize(file);
+		if (maxSize > 0 && file.size > maxSize) {
+			return Promise.reject(this._getTypeName(file) + '上传大小不能超过' + this._formatSize(maxSize) + ',请压缩后重新上传');
+		}
+
+		return Promise.resolve(file);
+	}
+
 	_shouldCompress(file) {
 		var quality = this.options.imageQuality || 'standard';
 		if (quality == 'origin') {
@@ -133,6 +149,41 @@ class MyUploadAdapter {
 		return 0.7;
 	}
 
+	_getMaxSize(file) {
+		if (this._isImage(file)) {
+			return parseInt(this.options.imageMaxSize || 20 * 1024 * 1024);
+		}
+		if (this._isVideo(file)) {
+			return parseInt(this.options.videoMaxSize || 1024 * 1024 * 1024);
+		}
+		return parseInt(this.options.fileMaxSize || 10 * 1024 * 1024);
+	}
+
+	_getTypeName(file) {
+		if (this._isImage(file)) {
+			return '图片';
+		}
+		if (this._isVideo(file)) {
+			return '视频';
+		}
+		return '文件';
+	}
+
+	_isImage(file) {
+		return (file.type && file.type.indexOf('image/') === 0) || /\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i.test(file.name || '');
+	}
+
+	_isVideo(file) {
+		return (file.type && file.type.indexOf('video/') === 0) || /\.(mp4|webm|ogg|ogv|mov|avi|wmv|flv|mkv|mpeg|mpg|rm|rmvb)$/i.test(file.name || '');
+	}
+
+	_formatSize(size) {
+		if (size >= 1024 * 1024 * 1024) {
+			return Math.round(size / 1024 / 1024 / 1024) + 'G';
+		}
+		return Math.round(size / 1024 / 1024) + 'M';
+	}
+
 	_compressImage(file) {
 		var maxWidth = parseInt(this.options.imageMaxWidth || 1920);
 		var qualityValue = this._getQualityValue();

+ 4 - 4
WebRoot/apps/space/plug-in/ueditor/jsp/config.json

@@ -3,7 +3,7 @@
     /* 上传图片配置项 */
     "imageActionName": "uploadimage", /* 执行上传图片的action名称 */
     "imageFieldName": "upfile", /* 提交的图片表单名称 */
-    "imageMaxSize": 31457280, /* 上传大小限制,单位B */
+    "imageMaxSize": 20971520, /* 上传大小限制,单位B,20M */
     "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
     "imageCompressEnable": true, /* 是否压缩图片,默认是true */
     "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
@@ -51,7 +51,7 @@
     "videoFieldName": "upfile", /* 提交的视频表单名称 */
     "videoPathFormat": "/web/upload/editor/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
     "videoUrlPrefix": "", /* 视频访问路径前缀 */
-    "videoMaxSize": 1073741824, /* 上传大小限制,单位B,默认100MB */
+    "videoMaxSize": 1073741824, /* 上传大小限制,单位B,1G */
     "videoAllowFiles": [
         ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
         ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */
@@ -61,7 +61,7 @@
     "fileFieldName": "upfile", /* 提交的文件表单名称 */
     "filePathFormat": "/web/upload/editor/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
     "fileUrlPrefix": "", /* 文件访问路径前缀 */
-    "fileMaxSize": 51200000, /* 上传大小限制,单位B,默认50MB */
+    "fileMaxSize": 10485760, /* 上传大小限制,单位B,10M */
     "fileAllowFiles": [
         ".png", ".jpg", ".jpeg", ".gif", ".bmp",
         ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
@@ -91,4 +91,4 @@
         ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
     ] /* 列出的文件类型 */
 
-}
+}

+ 56 - 14
WebRoot/main/ffkj-portal/portal-zq.js

@@ -219,6 +219,24 @@
       }
     }
 
+    function normalizeUploadMediaUrl(url, baseUrl) {
+      var normalized = normalizeUrl(url, baseUrl);
+      if (!normalized) return "";
+      try {
+        var parsed = new URL(normalized, window.location.href);
+        var uploadIndex = parsed.pathname.indexOf("/web/upload/");
+        if (uploadIndex >= 0) {
+          var uploadPath = parsed.pathname.slice(uploadIndex).replace(/\/{2,}/g, "/");
+          return window.location.origin + uploadPath + parsed.search + parsed.hash;
+        }
+      } catch (error) {
+        normalized = String(normalized).replace(/^(?:https?:)?\/\/[^/]*(\/web\/upload\/.*)$/i, "$1");
+        normalized = normalized.replace(/^(https?:)\/+(\/web\/upload\/.*)$/i, "$2");
+        normalized = normalized.replace(/(\/web\/upload\/modules)\/+/i, "$1/");
+      }
+      return normalized;
+    }
+
     function isDirectVideoUrl(url) {
       return directVideoPattern.test(url || "");
     }
@@ -237,6 +255,33 @@
       return isDirectVideoUrl(url) ? "video" : "iframe";
     }
 
+    function requestText(url) {
+      if (window.fetch) {
+        return window.fetch(url, { credentials: "same-origin" }).then(function (response) {
+          if (!response.ok) throw new Error("Video detail request failed");
+          return response.text();
+        });
+      }
+
+      return new Promise(function (resolve, reject) {
+        var xhr = new XMLHttpRequest();
+        xhr.open("GET", url, true);
+        xhr.withCredentials = true;
+        xhr.onreadystatechange = function () {
+          if (xhr.readyState !== 4) return;
+          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) {
+            resolve(xhr.responseText);
+          } else {
+            reject(new Error("Video detail request failed"));
+          }
+        };
+        xhr.onerror = function () {
+          reject(new Error("Video detail request failed"));
+        };
+        xhr.send();
+      });
+    }
+
     function findMediaFromArticle(html, baseUrl) {
       var doc = new DOMParser().parseFromString(html, "text/html");
       var root = doc.querySelector(".article-body") || doc;
@@ -248,13 +293,13 @@
 
       if (mediaNode) {
         match = mediaNode.getAttribute("src");
-        if (match) return { type: "video", url: normalizeUrl(match, baseUrl) };
+        if (match) return { type: "video", url: normalizeUploadMediaUrl(match, baseUrl) };
       }
 
       for (var i = 0; i < links.length; i += 1) {
         match = links[i].getAttribute("href");
         if (isDirectVideoUrl(match)) {
-          return { type: "video", url: normalizeUrl(match, baseUrl) };
+          return { type: "video", url: normalizeUploadMediaUrl(match, baseUrl) };
         }
       }
 
@@ -265,7 +310,7 @@
 
       textMatch = (root.textContent || "").match(/https?:\/\/\S+\.(mp4|webm|ogg|m4v|mov|m3u8)(\?\S*)?/i);
       if (textMatch) {
-        return { type: "video", url: normalizeUrl(textMatch[0], baseUrl) };
+        return { type: "video", url: normalizeUploadMediaUrl(textMatch[0], baseUrl) };
       }
 
       return null;
@@ -302,20 +347,21 @@
 
     function openPlayer(media, card) {
       var poster = card.getAttribute("data-video-poster") || "";
+      var mediaUrl = media.type === "video" ? normalizeUploadMediaUrl(media.url) : normalizeUrl(media.url);
       var element = null;
       openShell(card);
       stage.innerHTML = "";
-      syncDetailLink(card, media.url);
+      syncDetailLink(card, mediaUrl);
 
-      if (getMediaType(media.url, media.type) === "iframe") {
+      if (getMediaType(mediaUrl, media.type) === "iframe") {
         element = document.createElement("iframe");
-        element.src = media.url;
+        element.src = mediaUrl;
         element.title = titleNode.textContent;
         element.allow = "autoplay; fullscreen; picture-in-picture";
         element.allowFullscreen = true;
       } else {
         element = document.createElement("video");
-        element.src = media.url;
+        element.src = mediaUrl;
         element.controls = true;
         element.autoplay = true;
         element.playsInline = true;
@@ -360,11 +406,11 @@
       var directUrl = card.getAttribute("data-video-url") || "";
       if (!directUrl && isDirectVideoUrl(card.href)) directUrl = card.href;
       if (directUrl) {
-        openPlayer({ type: "video", url: normalizeUrl(directUrl) }, card);
+        openPlayer({ type: "video", url: normalizeUploadMediaUrl(directUrl) }, card);
         return;
       }
 
-      if (!isSameOriginPage(card.href) || !window.fetch) {
+      if (!isSameOriginPage(card.href)) {
         followCard(card);
         return;
       }
@@ -373,11 +419,7 @@
         openLoading(card);
       }, 180);
 
-      window.fetch(card.href, { credentials: "same-origin" })
-        .then(function (response) {
-          if (!response.ok) throw new Error("Video detail request failed");
-          return response.text();
-        })
+      requestText(card.href)
         .then(function (html) {
           var media = findMediaFromArticle(html, card.href);
           window.clearTimeout(loadingTimer);

+ 1 - 1
WebRoot/web/upload/ffkj-template/screen-index.jsp

@@ -10,7 +10,7 @@
 <c:set var="screenPortalJsVersion" value="20260623-hero-wheel-return"/>
 <c:if test="${portalThemeClass eq 'screen-red-theme'}">
 	<c:set var="screenPortalCssVersion" value="20260626-screen-red-colorful-video"/>
-	<c:set var="screenPortalJsVersion" value="20260626-screen-red-colorful-video"/>
+	<c:set var="screenPortalJsVersion" value="20260627-screen-red-video-xhr-normalize"/>
 </c:if>
 <!doctype html>
 <html lang="zh-CN">

+ 167 - 0
src/space/core/apps/sys/service/UploadService.java

@@ -0,0 +1,167 @@
+package space.core.apps.sys.service;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.UUID;
+
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileUploadBase;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+
+import space.common.exception.SpaceRuntimeException;
+import space.core.apps.common.BaseTransaction;
+import space.core.apps.sys.utils.UploadFileUtil;
+import space.core.common.CommonVars;
+import space.core.common.utils.GsonUtil;
+import space.core.common.utils.ThumbnailatorUtil;
+
+public class UploadService extends BaseTransaction {
+	private static final long serialVersionUID = 1L;
+
+	private static final long IMAGE_MAX_SIZE = 20L * 1024L * 1024L;
+	private static final long VIDEO_MAX_SIZE = 1024L * 1024L * 1024L;
+	private static final long DEFAULT_MAX_SIZE = 10L * 1024L * 1024L;
+
+	public void ajaxUpload() throws IOException {
+		Map<String, Object> result = new HashMap<String, Object>();
+
+		try {
+			DiskFileItemFactory factory = new DiskFileItemFactory();
+			File tempDir = new File(CommonVars.getWebRootPath() + "/web/upload/modules/sys/temp/");
+			if (!tempDir.exists()) {
+				tempDir.mkdirs();
+			}
+			factory.setSizeThreshold(40960);
+			factory.setRepository(tempDir);
+
+			ServletFileUpload upload = new ServletFileUpload(factory);
+			upload.setHeaderEncoding("UTF-8");
+			upload.setFileSizeMax(VIDEO_MAX_SIZE);
+
+			List<FileItem> items = upload.parseRequest(getRequest());
+			List<Map<String, String>> data = new ArrayList<Map<String, String>>();
+			String uploadPath = UploadFileUtil.getUploadFilePath(getWebApp(), "files");
+			File uploadDir = new File(CommonVars.getWebRootPath() + uploadPath);
+			if (!uploadDir.exists()) {
+				uploadDir.mkdirs();
+			}
+
+			for (FileItem item : items) {
+				if (!item.isFormField()) {
+					data.add(uploadForAjax(item, uploadPath));
+				}
+			}
+
+			result.put("code", "success");
+			result.put("msg", "上传成功");
+			result.put("data", data);
+			getWriter().write(GsonUtil.toJson(result));
+		} catch (SpaceRuntimeException e) {
+			result.put("code", "fail");
+			result.put("msg", e.getMessage());
+			getWriter().write(GsonUtil.toJson(result));
+		} catch (FileUploadBase.FileSizeLimitExceededException e) {
+			result.put("code", "fail");
+			result.put("msg", "单个文件上传大小不能超过1G,请压缩后重新上传");
+			getWriter().write(GsonUtil.toJson(result));
+		} catch (Exception e) {
+			result.put("code", "fail");
+			result.put("msg", "上传失败");
+			getWriter().write(GsonUtil.toJson(result));
+			e.printStackTrace();
+		}
+	}
+
+	private Map<String, String> uploadForAjax(FileItem item, String uploadPath) throws Exception {
+		Map<String, String> result = new HashMap<String, String>();
+		String originalName = normalizeFileName(item.getName());
+		long fileSize = item.getSize();
+		validateUploadFile(originalName, item.getContentType(), fileSize);
+
+		String suffix = getSuffix(originalName);
+		String targetPath = uploadPath + UUID.randomUUID().toString().replace("-", "") + suffix;
+		File targetFile = new File(CommonVars.getWebRootPath() + targetPath);
+		item.write(targetFile);
+
+		compressImage(targetFile);
+
+		result.put("code", "success");
+		result.put("msg", targetPath);
+		return result;
+	}
+
+	private void validateUploadFile(String fileName, String contentType, long fileSize) throws SpaceRuntimeException {
+		if (fileName.length() == 0 || fileSize <= 0) {
+			throw new SpaceRuntimeException("请选择有效的上传文件");
+		}
+
+		String lowerName = fileName.toLowerCase(Locale.ENGLISH);
+		if (lowerName.matches(".*\\.(jsp|jspx|html|php|asp|aspx|exe)$")) {
+			throw new SpaceRuntimeException("该文件类型不允许上传");
+		}
+
+		long maxSize = DEFAULT_MAX_SIZE;
+		String fileType = "文件";
+		String maxSizeText = "10M";
+		if (isImageFile(lowerName, contentType)) {
+			maxSize = IMAGE_MAX_SIZE;
+			fileType = "图片";
+			maxSizeText = "20M";
+		} else if (isVideoFile(lowerName, contentType)) {
+			maxSize = VIDEO_MAX_SIZE;
+			fileType = "视频";
+			maxSizeText = "1G";
+		}
+
+		if (fileSize > maxSize) {
+			throw new SpaceRuntimeException(fileType + "上传大小不能超过" + maxSizeText + ",请压缩后重新上传");
+		}
+	}
+
+	private String normalizeFileName(String fileName) {
+		if (fileName == null) {
+			return "";
+		}
+		String normalized = fileName.replaceAll("\\s+", "_");
+		int slashIndex = Math.max(normalized.lastIndexOf("\\"), normalized.lastIndexOf("/"));
+		if (slashIndex >= 0 && slashIndex + 1 < normalized.length()) {
+			normalized = normalized.substring(slashIndex + 1);
+		}
+		return normalized;
+	}
+
+	private String getSuffix(String fileName) {
+		int dotIndex = fileName.lastIndexOf(".");
+		if (dotIndex < 0 || dotIndex == fileName.length() - 1) {
+			return "";
+		}
+		return fileName.substring(dotIndex);
+	}
+
+	private boolean isImageFile(String lowerName, String contentType) {
+		return startsWithIgnoreCase(contentType, "image/")
+				|| lowerName.matches(".*\\.(jpg|jpeg|png|gif|bmp|webp|svg)$");
+	}
+
+	private boolean isVideoFile(String lowerName, String contentType) {
+		return startsWithIgnoreCase(contentType, "video/")
+				|| lowerName.matches(".*\\.(mp4|webm|ogg|ogv|mov|avi|wmv|flv|mkv|mpeg|mpg|rm|rmvb)$");
+	}
+
+	private boolean startsWithIgnoreCase(String value, String prefix) {
+		return value != null && value.toLowerCase(Locale.ENGLISH).startsWith(prefix);
+	}
+
+	void compressImage(File file) throws IOException {
+		if (!ThumbnailatorUtil.isImage(file)) {
+			return;
+		}
+		ThumbnailatorUtil.compress(file);
+	}
+}