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

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

原文链接:https://blog.csdn.net/qq_43419105/java/article/details/90755402

源码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

成果:

猜你喜欢

转载自www.cnblogs.com/zxy-come-on/p/12753202.html