Ueditor upload of single pictures, multiple pictures, videos, attachments and online management summary

The previous article has mentioned the benefits of Ueditor Baidu's rich text plug-in, which is not too long-winded here, mainly to say that Ueditor is aimed at Ueditor single picture, multi-picture, video upload and their corresponding online in Java development Summary of management issues and codes.
Ueditor uploads single file, multi-picture, video, and file in the form of file attachments of type String. Three points can be briefly summarized: the
first step: first look at the settings for the uploaded image configuration item in config.json, view imageActionName, imageFileName, imagePathFormat; the
second step: whether to upload pictures and videos, all are uploaded in the form of file attachments
Yes , so check the attachment configuration items and attachment paths, etc .; Step 3: View the source image.js and look at the return type of ajax, add what you need; Prerequisite: result.put ("state", "SUCCESS" );
Next step by step analysis!

Original link: https://blog.csdn.net/qq_43419105/java/article/details/90755402

 

 

Source config.json configuration items

/ * Upload image configuration item * /
"imageActionName": "/ attachment / uploadbd", / * the name of the action to upload the image * /
"imageFieldName": "upfile", / * the name of the submitted image form * /
"imageMaxSize": 2048000, / * Upload size limit, unit B * /
"imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], / * Upload image format display * /
"imageCompressEnable": true, / * whether to compress the image, the default is true * /
"imageCompressBorder": 1600, / * the image compression longest side limit * /
"imageInsertAlign": "none", / * the floating method of the inserted image /
"imageUrlPrefix": "", / * Image access path prefix * /
"imagePathFormat": "/../UEditor_jsp/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6 } ", / * Upload save path,You can customize the save path and file name format * /
/ * {filename} will be replaced with the original file name, configuration needs to pay attention to the Chinese garbled problem * /
/ * {rand: 6} will be replaced with a random number, and the numbers behind are random The number of digits * /
/ * {time} will be replaced with a timestamp * /
/ * {yyyy} will be replaced with a four-digit year * /
/ * {yy} will be replaced by two years * /
/ * {mm} will be replaced by two months * /
/ * {dd} will be replaced by two days * /
/ * {hh} will be replaced by two hours * /
/ * {ii} will be replaced by two minutes * /
/ * {ss} will be replaced by two seconds * /
/ * Illegal characters \: *? "<> | * /
/ * Please watch online Document: fex.baidu.com/ueditor/#use-format_upload_filename * /

/ * Upload video configuration * /
"videoActionName": "video", / * Action name for uploading video * /
"videoFieldName": "upfile", / * The name of the submitted video form * /
"videoPathFormat": "/ ueditor / jsp / upload / video / {yyyy} {mm} {dd} / {time} {rand: 6}", / * Upload and save the path, you can choose Define the save path and file name format * /
"videoUrlPrefix": "", / * video access path prefix * /
"videoMaxSize": 102400000, / * upload size limit, unit B, default 100MB * /
"videoAllowFiles": [
". flv "," .swf ", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], / * upload video Format display * /

/ * Upload file configuration * /
"fileActionName": "uploadfile", / * the name of the action to execute the uploaded video in the controller * /
"fileFieldName": "upfile", / * the name of the submitted file form * /
"filePathFormat": " / ueditor / jsp / upload / file / {yyyy} {mm} {dd} / {time} {rand: 6} ", / * Upload save path, you can customize the save path and file name format * /
" fileUrlPrefix ": "", / * File access path prefix * /
"fileMaxSize": 51200000, / * upload size limit, unit B, default 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"
], /* 上传文件格式显示 */".md", ".xml" ], / * Upload file format display * /".md", ".xml" ], / * Upload file format display * /

/* 列出指定目录下的图片 在线管理预览 */
"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"
] /* 列出的文件类型 */

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Source controller.jsp configuration items

<%

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 );

%>
Note: (action.equals ("listfile") || listfile and listimage in action.equals ("listimage"), corresponding to fileActionName in config.json

 

 

 

 

 

 

 

 

 

 

Service layer code:

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("对不起,不支持上传此类型文件!");
}
}
Note: The video pictures can be displayed directly. After the attachment is uploaded, it needs to be downloaded before it can be displayed;

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Ueditor integrates Spring Boot's UeditorController class

 

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;
}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Description:

当不知道返回给页面的所需参数时,我们可以查看针对源码的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

 

 

 

 

 

 

 

 

 

 

 

 

When uploading a video, you need to set the size of the uploaded video application.properties

# The size of the file upload allowed spring.http.multipart.maxFileSize = 100Mb spring.http.multipart.maxRequestSize = 100Mb

 

Results:

 

Guess you like

Origin www.cnblogs.com/zxy-come-on/p/12753202.html