Ueditor 单图、多图、视频、附件的上传及在线管理总结

简介

上一篇文章已经提到了Ueditor百度的富文本插件的好处,在这里就不多啰嗦了,主要来说说Ueditor在java开发中针对Ueditor 单图、多图、视频的上传及其所对应的在线管理问题及代码的总结。
Ueditor在进行单图、多图、视频、文件上传的时候都是以String类型的文件附件的形式上传的。可以简单总结三点:
		第一步:首先看  config.json中针对上传图片配置项设置,查看imageActionName、imageFileName、imagePathFormat;
		第二步:不管是上传图片、视频、都是以文件附件的形式来上传的,所以查看附件配置项以及附件路径等等;
		第三步:查看源码的image.js看起ajax的返回类型,需要啥就补充啥;前提条件:result.put("state", "SUCCESS");
接下来一步一步分析吧!

源码config.json配置项

    /* 上传图片配置项 */
    "imageActionName": "/attachment/uploadbd", /* 执行上传图片的action名称 */
    "imageFieldName": "upfile", /* 提交的图片表单名称 */
    "imageMaxSize": 2048000, /* 上传大小限制,单位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
    "imageCompressEnable": true, /* 是否压缩图片,默认是true */
    "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
    "imageInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageUrlPrefix": "", /* 图片访问路径前缀 */
    "imagePathFormat": "/../UEditor_jsp/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
                                /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
                                /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
                                /* {time} 会替换成时间戳 */
                                /* {yyyy} 会替换成四位年份 */
                                /* {yy} 会替换成两位年份 */
                                /* {mm} 会替换成两位月份 */
                                /* {dd} 会替换成两位日期 */
                                /* {hh} 会替换成两位小时 */
                                /* {ii} 会替换成两位分钟 */
                                /* {ss} 会替换成两位秒 */
                                /* 非法字符 \ : * ? " < > | */
                                /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */
                     
       /* 上传视频配置 */
    "videoActionName": "video", /* 执行上传视频的action名称 */
    "videoFieldName": "upfile", /* 提交的视频表单名称 */
    "videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "videoUrlPrefix": "", /* 视频访问路径前缀 */
    "videoMaxSize": 102400000, /* 上传大小限制,单位B,默认100MB */
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */

    /* 上传文件配置 */
    "fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */
    "fileFieldName": "upfile", /* 提交的文件表单名称 */
    "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "fileUrlPrefix": "", /* 文件访问路径前缀 */
    "fileMaxSize": 51200000, /* 上传大小限制,单位B,默认50MB */
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ], /* 上传文件格式显示 */

    /* 列出指定目录下的图片     在线管理预览 */
    "imageManagerActionName": "/images/attachment/", /* 执行图片管理的action名称 */
    "imageManagerListPath": "/ueditor/jsp/upload/image/", /* 指定要列出图片的目录 */
    "imageManagerListSize": 20, /* 每次列出文件数量 */
    "imageManagerUrlPrefix": "", /* 图片访问路径前缀 */
    "imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */

    /* 列出指定目录下的文件    在线管理预览*/
    "fileManagerActionName": "listfile", /* 执行文件管理的action名称 */
    "fileManagerListPath": "/ueditor/jsp/upload/file/", /* 指定要列出文件的目录 */
    "fileManagerUrlPrefix": "", /* 文件访问路径前缀 */
    "fileManagerListSize": 20, /* 每次列出文件数量 */
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ] /* 列出的文件类型 */

源码controller.jsp配置项

<%

    request.setCharacterEncoding( "utf-8" );
	response.setHeader("Content-Type" , "text/html");
	
	String rootPath = application.getRealPath( "/" );
	
	String action = request.getParameter("action");  
    String result = new ActionEnter( request, rootPath ).exec();  
    if( action!=null && (action.equals("listfile") || action.equals("listimage") ) ){  
        rootPath = rootPath.replace("\\", "/");  
        result = result.replaceAll(rootPath, "/");//把返回路径中的物理路径替换为 '/'  
    }  
    out.write( result );

%>
注:(action.equals("listfile") || action.equals("listimage")中的listfile与listimage,对应的是config.json中的fileActionName

service方法


	public String uploadImage(MultipartFile file, String originalFilename, String type, Member member) throws Exception {
		//判断文件是否允许呗
        if (this.getAllowFileType().contains("." + FilenameUtils.getExtension(file.getOriginalFilename()))) {
        	//新文件名
            String fileName = UUIDUtil.creatUUID()  + type;
            File rfile = ResourceUtils.getFile("classpath:static");
            String lastPath = rfile.getAbsolutePath() + "\\images\\attachment\\" + fileName;
            //判断存储路径是否已经存在,不存在则需要先创建出来
            try {
                //将文件存储到实际存储目录中
            	FileUtils.copyInputStreamToFile(file.getInputStream(), new File(lastPath));
            	Attachment att = new Attachment();
            	att.setOriginalName(originalFilename);
            	att.setSuffix(type);
            	att.setFileSize(file.getSize());
            	att.setContentType(type);
            	att.setMember(member);
            	att.setUploadTime(new Date());
                att.setFilePath("images/attachment/" + fileName);
                attachmentDao.save(att);
            } catch (Exception e) {
                logger.error("上传文件存储失败!", e);
                throw new Exception("上传文件存储失败", e);
            }
            return "images/attachment/" + fileName;
        } else {
            throw new Exception("对不起,不支持上传此类型文件!");
        }
	}
	//视频上传
	public String uploadVideo(MultipartFile file, String originalFilename, String type, Member member) throws Exception {
		//判断文件是否允许呗
        if (this.getAllowFileType().contains("." + FilenameUtils.getExtension(file.getOriginalFilename()))) {
        	//新文件名
            String fileName = UUIDUtil.creatUUID()  + type;
            File rfile = ResourceUtils.getFile("classpath:static");
            String lastPath = rfile.getAbsolutePath() + "\\video\\attachment\\" + fileName;
            //判断存储路径是否已经存在,不存在则需要先创建出来
            try {
                //将文件存储到实际存储目录中
            	FileUtils.copyInputStreamToFile(file.getInputStream(), new File(lastPath));
            	Attachment att = new Attachment();
            	att.setOriginalName(originalFilename);
            	att.setSuffix(type);
            	att.setFileSize(file.getSize());
            	att.setContentType("视频");
            	att.setMember(member);
            	att.setUploadTime(new Date());
                att.setFilePath("video/attachment/" + fileName);
                attachmentDao.save(att);
            } catch (Exception e) {
                logger.error("上传文件存储失败!", e);
                throw new Exception("上传文件存储失败", e);
            }
            return "video/attachment/" + fileName;
        } else {
            throw new Exception("对不起,不支持上传此类型文件!");
        }
	}
	
	//上传附件
	public String uploadAttachment(MultipartFile file, String originalFilename, String type, Member member) throws Exception {
		//判断文件是否允许呗
        if (this.getAllowFileType().contains("." + FilenameUtils.getExtension(file.getOriginalFilename()))) {
        	//新文件名
            String fileName = UUIDUtil.creatUUID()  + type;
            File rfile = ResourceUtils.getFile("classpath:static");
            String lastPath = rfile.getAbsolutePath() + "\\files\\attachment\\" + fileName;
            //判断存储路径是否已经存在,不存在则需要先创建出来
            try {
                //将文件存储到实际存储目录中
            	FileUtils.copyInputStreamToFile(file.getInputStream(), new File(lastPath));
            	Attachment att = new Attachment();
            	att.setOriginalName(originalFilename);
            	att.setSuffix(type);
            	att.setFileSize(file.getSize());
            	att.setContentType("附件");
            	att.setMember(member);
            	att.setUploadTime(new Date());
                att.setFilePath("files/attachment/" + fileName);
                attachmentDao.save(att);
            } catch (Exception e) {
                logger.error("上传文件存储失败!", e);
                throw new Exception("上传文件存储失败", e);
            }
            return "files/attachment/" + fileName;
        } else {
            throw new Exception("对不起,不支持上传此类型文件!");
        }
	}
	注:视频图片是可以直接显示的,附件上传之后需要下载之后才可以显示出来;

Ueditor整合Spring Boot 的 UeditorController类

package cn.gson.crm.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.servlet.ModelAndView;

import cn.gson.crm.common.Base64Utils;
import cn.gson.crm.common.Constants;
import cn.gson.crm.common.UUIDUtil;
import cn.gson.crm.model.dao.AttachmentDao;
import cn.gson.crm.model.domain.Attachment;
import cn.gson.crm.model.domain.Member;
import cn.gson.crm.service.AttachmentService;

/**
 * 描述:Ueditor整合spring boot实现方法
 * 功能:图片的上传、预览,视屏的上传,附件的上传、预览,
 * 注:图片预览只针对 ".png", ".jpg", ".jpeg", ".gif", ".bmp"
 * 	  附件预览只针对 压缩文件,word文档,Excel文件,PPT,txt文件
 * 
 * @author fyh
 * 
 */

@Controller
@RequestMapping("/UEditor_jsp")
public class UeditorController {
	
	@Autowired
    AttachmentService attachmentService;
	//附件上传的dao
	@Autowired
	AttachmentDao attachmentDao;
	

    @RequestMapping("/config")
    @ResponseBody
    public Object config(String action, HttpServletRequest request, HttpServletResponse response, HttpSession session , String scwalfile) throws Exception {
    	
    	Member member = (Member)session.getAttribute(Constants.SESSION_MEMBER_KEY);
        Map<String, Object> result = new HashMap<String, Object>();
        if ("config".equals(action))
        {
        	ModelAndView mv = new ModelAndView("redirect:/UEditor_jsp/jsp/config.json");
        	return mv;
        }
        //单图上传与多图上传
        else if("/attachment/uploadbd".equals(action))
        {
        	try {
                MultipartRequest multipartRequest = (MultipartRequest) request;
                MultipartFile file = multipartRequest.getFile("upfile");
                String originalFilename = file.getOriginalFilename();
                String fileType = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
                byte[] bytes = IOUtils.toByteArray(file.getInputStream());
                String vivofsImagePath = attachmentService.uploadImage(file, originalFilename, fileType, member);
                result.put("state", "SUCCESS");
                result.put("name", originalFilename);
                result.put("original", originalFilename);
                result.put("size", bytes.length);
                result.put("type", fileType);
                result.put("url", vivofsImagePath);
            } catch (Exception e) {
                result.put("state", "FAILED");
            }
        }
        //图片在线预览
        else if ("/images/attachment/".equals(action))
        {
        	try {
        		List<Map<String, String>> imgList = new ArrayList<Map<String, String>>();
        		
        		Iterable<Attachment> findAll = attachmentDao.findAll();
        		for(Attachment attachmentList : findAll){
        			Map<String, String> map = new HashMap<>();
        			String filePath = "/" +attachmentList.getFilePath();
        			String aftername = filePath.substring(filePath.lastIndexOf("."));
        			if(aftername.equals(".png") || aftername.equals(".jpg") || aftername.equals(".jpeg") || aftername.equals(".gif") || aftername.equals(".bpm")){
        				map.put("url", filePath);
                		imgList.add(map);
        			}
        		}
            	int start = 0;
            	int total = 10;
            	result.put("state", "SUCCESS");
            	result.put("list", imgList); //图片路径列表
            	result.put("start", start); //图片开始位置
            	result.put("total", total); //图片总数
            } catch (Exception e) {
                result.put("state", "FAILED");
            }
        }
        //上传视频
        else if("video".equals(action))
        {
        	try {
        		MultipartRequest multipartRequest = (MultipartRequest) request;
                MultipartFile file = multipartRequest.getFile("upfile");
                String originalFilename = file.getOriginalFilename();
                String fileType = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
                String videoPath = attachmentService.uploadVideo(file, originalFilename, fileType, member);
                result.put("state", "SUCCESS");
                result.put("url", videoPath);
                result.put("type", fileType);
                result.put("original", originalFilename);
                
			} catch (Exception e) {
				result.put("state", "FAILED");
			}
        	 
        }
        //上传附件,注附件在下载只有才可以浏览,初步尝试为Excel文件
        else if("uploadfile".equals(action))
        {
        	try {
        		MultipartRequest multipartRequest = (MultipartRequest) request;
                MultipartFile file = multipartRequest.getFile("upfile");
                String originalFilename = file.getOriginalFilename();
                String fileType = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
                String uploadAttachment = attachmentService.uploadAttachment(file, originalFilename, fileType, member);
                result.put("state", "SUCCESS");
                result.put("name", originalFilename);
                result.put("original", originalFilename);
                result.put("type", fileType);
                result.put("url", uploadAttachment);
                
			} catch (Exception e) {
				result.put("state", "FAILED");
			}
        }
        //附件在线预览
        else if("listfile".equals(action))
        {
        	try {
        		List<Map<String, String>> fileList = new ArrayList<Map<String, String>>();
        		//查找到附件表中的所有数据
        		Iterable<Attachment> findAll = attachmentDao.findAll();
        		for(Attachment attachmentList : findAll){
        			Map<String, String> map = new HashMap<>();
        			String filePath = attachmentList.getFilePath();
        			String aftername = filePath.substring(filePath.lastIndexOf("."));
        			//附件预览展示页面文件所要满足的条件
        			if(aftername.equals(".docx") || aftername.equals(".xlsx") || aftername.equals(".doc") || aftername.equals(".pdf")
        					 || aftername.equals(".rar") || aftername.equals(".zip") || aftername.equals(".ppt") || aftername.equals(".pptx")
        					 || aftername.equals(".txt")){
        				map.put("url", filePath);
        				fileList.add(map);
        			}
        		}
            	int start = 0;
            	int total = 10;
            	result.put("state", "SUCCESS");
            	result.put("list", fileList); //图片路径列表
            	result.put("start", start); //图片开始位置
            	result.put("total", total); //图片总数
            } catch (Exception e) {
                result.put("state", "FAILED");
            }
        	
        }
        return result;
    }

}

说明

 当不知道返回给页面的所需参数时,我们可以查看针对源码的js文件看其ajax请求。以video.js为例
  uploader.on('uploadSuccess', function (file, ret) {
                var $file = $('#' + file.id);
                try {
                    var responseText = (ret._raw || ret),
                        json = utils.str2json(responseText);
                    if (json.state == 'SUCCESS') {
                        uploadVideoList.push({
                            'url': json.url,
                            'type': json.type,
                            'original':json.original
                        });
                        $file.append('<span class="success"></span>');
                    } else {
                        $file.find('.error').text(json.state).show();
                    }
                } catch (e) {
                    $file.find('.error').text(lang.errorServerUpload).show();
                }
            });
      从这段源码中我们可以看到,其需要  url 、type、original

在上传视频时需要设置上传视频的大小application.properties

# 允许文件上传的尺寸大小
spring.http.multipart.maxFileSize=100Mb
spring.http.multipart.maxRequestSize=100Mb

成果展示

在这里插入图片描述
在这里插入图片描述

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring中实现UEditor片上可以参考以下步骤: 1. 在前端Vue代码中配置UEditor富文本编辑器,并对上片做出相关设置。 2. 在Spring后端代码中编写片上的控制器,处理前端递的片文件信息。 3. 在Spring配置文件中配置文件上的相关参数。 下面是具体的实现方法: 1. 前端代码: 在Vue组件中引入UEditor富文本编辑器,可以使用UEditor官网提供的Vue UEditor Wrapper组件。并在UEditor配置项中设置上片的相关参数,如下所示: ``` <template> <div> <vue-ueditor-wrap v-model="content" :config="ueditorConfig" :z-index="100" ></vue-ueditor-wrap> </div> </template> <script> import VueUeditorWrap from 'vue-ueditor-wrap'; export default { components: { VueUeditorWrap }, data () { return { content: '', ueditorConfig: { UEDITOR_HOME_URL: '/static/UEditor/', serverUrl: '/api/upload', maximumWords: 50000, initialFrameWidth: '100%', initialFrameHeight: 500, autoHeightEnabled: false, autoFloatEnabled: false, toolbars: [ ['source', 'bold', 'italic', 'underline', 'strikethrough', 'removeformat', 'formatmatch', 'forecolor', 'backcolor', 'fontfamily', 'fontsize', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', 'touppercase', 'tolowercase', 'link', 'unlink', 'insertimage', 'emotion', 'scrawl', 'music', 'insertvideo', 'attachment', 'map', 'gmap', 'insertcode', 'template', 'background', 'date', 'time', 'spechars', 'searchreplace', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts' ] ] }, }; }, }; </script> ``` 在上述代码中,通过`serverUrl`参数设置了上片的后端接口地址为`/api/upload`。 2. 后端控制器代码: 在Spring中,可以通过编写一个控制器方法来实现UEditor片的功能。具体代码如下: ``` @RequestMapping(value = "/api/upload", method = RequestMethod.POST) @ResponseBody public String uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("utf-8"); response.setHeader("Content-Type", "text/html"); String rootPath = request.getSession().getServletContext().getRealPath("/"); String contextPath = request.getContextPath(); String basePath = rootPath + File.separator + "upload" + File.separator; String savePath = contextPath + "/upload/"; String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"}; String upfile = "upfile"; JSONObject result = new JSONObject(); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Iterator<String> iterator = multipartRequest.getFileNames(); while (iterator.hasNext()) { MultipartFile file = multipartRequest.getFile(iterator.next()); if (file != null) { String fileName = file.getOriginalFilename(); String fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase(); boolean isAllow = false; for (String ext : fileType) { if (ext.equals(fileExt)) { isAllow = true; break; } } if (!isAllow) { result.put("state", "不支持的文件类型!"); return result.toJSONString(); } String newFileName = UUID.randomUUID().toString() + fileExt; File uploadedFile = new File(basePath, newFileName); if (!uploadedFile.getParentFile().exists()) { uploadedFile.getParentFile().mkdirs(); } file.transferTo(uploadedFile); result.put("state", "SUCCESS"); result.put("url", savePath + newFileName); result.put("title", newFileName); result.put("original", fileName); result.put("type", fileExt); result.put("size", file.getSize()); } } return result.toJSONString(); } ``` 3. Spring配置文件: 在Spring的配置文件中,需要配置文件上的相关参数。具体代码如下: ``` <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"/> <property name="defaultEncoding" value="UTF-8"/> <property name="resolveLazily" value="true"/> </bean> ``` 其中,`maxUploadSize`参数设置了上文件的最大大小,位为字节。 至此,我们就完成了在Spring+Vue中实现UEditor片上的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值