Carga del editor de imágenes individuales, imágenes múltiples, videos, archivos adjuntos y resumen de administración en línea

El artículo anterior ha mencionado los beneficios del complemento de texto enriquecido de Ueditor Baidu, que no tiene demasiada extensión aquí, principalmente para decir que Ueditor está dirigido a Ueditor, imagen única, imagen múltiple, carga de video y su correspondiente en línea Resumen de problemas de gestión y códigos.
Ueditor carga archivos individuales, múltiples imágenes, videos y archivos en forma de archivos adjuntos de tipo String. Se pueden resumir brevemente tres puntos: el
primer paso: primero mire la configuración del elemento de configuración de la imagen cargada en config.json, vea imageActionName, imageFileName, imagePathFormat; el
segundo paso: si cargar imágenes, videos, se cargan en forma de archivo adjunto
, así que verifique los elementos de configuración del archivo adjunto y las rutas del archivo adjunto, etc.; Paso 3: Vea la imagen image.js y observe el tipo de retorno de ajax, agregue lo que necesita; Requisito previo: result.put ("estado", "ÉXITO" ); ¡
Siguiente análisis paso a paso!

Enlace original: https://blog.csdn.net/qq_43419105/java/article/details/90755402

 

 

Elementos de configuración de config.json de origen

/ * Cargar elemento de configuración de imagen * /
"imageActionName": "/ attach / uploadbd", / * el nombre de la acción para cargar la imagen * /
"imageFieldName": "upfile", / * el nombre del formulario de imagen enviado * /
"imageMaxSize": 2048000, / * Límite de tamaño de carga, unidad B * /
"imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], / * Visualización del formato de carga de imagen * /
"imageCompressEnable": verdadero, / * si se comprime la imagen, el valor predeterminado es verdadero * /
"imageCompressBorder": 1600, / * el límite lateral más largo de compresión de imagen * /
"imageInsertAlign": "ninguno", / * el método flotante de la imagen insertada * /
"imageUrlPrefix": "", / * Prefijo de ruta de acceso de imagen * /
"imagePathFormat": "/../UEditor_jsp/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6 } ", / * Subir ruta de guardado,Puede personalizar la ruta de guardado y el formato de nombre de archivo * /
/ * {filename} se reemplazará con el nombre de archivo original, la configuración debe prestar atención al problema confuso chino * /
/ * {rand: 6} se reemplazará con un número aleatorio, y los números detrás son aleatorios El número de dígitos * /
/ * {hora} se reemplazará con una marca de tiempo * /
/ * {aaaa} se reemplazará con un año de cuatro dígitos * /
/ * {aa} será reemplazado por dos años * /
/ * {mm} será reemplazado por dos meses * /
/ * {dd} será reemplazado por dos días * /
/ * {hh} será reemplazado por dos horas * /
/ * {ii} se reemplazará por dos minutos * /
/ * {ss} se reemplazará por dos segundos * /
/ * caracteres ilegales \: *? "<> | * /
/ * Consulte en línea Documento: fex.baidu.com/ueditor/#use-format_upload_filename * /

/ * Cargar configuración de video * /
"videoActionName": "video", / * Nombre de acción para cargar video * /
"videoFieldName": "upfile", / * El nombre del formulario de video enviado * /
"videoPathFormat": "/ ueditor / jsp / upload / video / {aaaa} {mm} {dd} / {time} {rand: 6}", / * Cargue y guarde la ruta, puede elegir Defina la ruta de guardado y el formato de nombre de archivo * /
"videoUrlPrefix": "", / * prefijo de ruta de acceso de video * /
"videoMaxSize": 102400000, / * límite de tamaño de carga, unidad B, predeterminado 100MB * /
"videoAllowFiles": [
". flv "," .swf ", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], / * cargar video Formato de visualización * /

/ * Cargar configuración de archivo * /
"fileActionName": "uploadfile", / * el nombre de la acción para ejecutar el video cargado en el controlador * /
"fileFieldName": "upfile", / * el nombre del formulario de archivo enviado * /
"filePathFormat": " / ueditor / jsp / upload / file / {aaaa} {mm} {dd} / {time} {rand: 6} ", / * Subir ruta de guardado, puede personalizar la ruta de guardado y el formato de nombre de archivo * /
" fileUrlPrefix ": "", / * Prefijo de ruta de acceso a archivo * /
"fileMaxSize": 51200000, / * límite de tamaño de carga, unidad B, predeterminado 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" ], / * Visualización del formato de carga del archivo * /".md", ".xml" ], / * Visualización del formato de carga del archivo * /

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Elementos de configuración de la fuente controller.jsp

<%

request.setCharacterEncoding ("utf-8");
response.setHeader ("Content-Type", "text / html");

String rootPath = application.getRealPath ("/");

Cadena action = request.getParameter ("action");
Resultado de cadena = new ActionEnter (request, rootPath) .exec ();
if (action! = null && (action.equals ("listfile") || action.equals ("listimage"))) {
rootPath = rootPath.replace ("\\", "/");
result = result.replaceAll (rootPath, "/"); // 把 返回 路径 中 的 物理 路径 替换 为 '/'
}
out.write (resultado);

%>
Nota: (action.equals ("listfile") || listfile y listimage en action.equals ("listimage"), correspondiente a fileActionName en config.json

 

 

 

 

 

 

 

 

 

 

Código de capa de servicio:

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("对不起,不支持上传此类型文件!");
}
}
Nota: Las imágenes de video se pueden mostrar directamente. Después de cargar el archivo adjunto, debe descargarse antes de poder mostrarse;

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Ueditor integra la clase UeditorController de Spring Boot

 

paquete cn.gson.crm.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
importar 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;
}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Descripción:

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

 

 

 

 

 

 

 

 

 

 

 

 

Al cargar un video, debe establecer el tamaño de la aplicación de video cargada.

# El tamaño de la carga de archivos permitida spring.http.multipart.maxFileSize = 100Mb spring.http.multipart.maxRequestSize = 100Mb

 

Resultados:

 

Supongo que te gusta

Origin www.cnblogs.com/zxy-come-on/p/12753202.html
Recomendado
Clasificación