Download UEditor
Ueditor.baidu.com/website/dow…
Download the full source code and JSP version
Spring backend integration
1. Decompress the complete source code, copy the Java source code in the JSP directory to the Spring MVC back end
JSP directory Java source code
Integrate the Spring MVC back end
2. Configure config. Json
- Unzip the JSP version
- Copy config.json from JSP directory
- Put it in the Java project’s Resource directory, in this case uEditorConfig.json
- Config.json file name, in this case ueditorConfig.json
3. Project constant configuration file
- Create a new upload.properties file and place it under resouce:
# the host address
host=http://localhost:8081/ssm_project
File upload server address (IP + port)
uploadHost=http://localhost:8090/
Upload and save ordinary pictures
imagePath = fileUpload/image/
Upload and save the system user profile picture
headImgPath = fileUpload/image/headImg/
# Default profile picture of system user
sysUserDefImg = sysUser-default.jpg
Text file upload save directory
documentPath = fileUpload/document/
Upload and save audio files
soundPath = fileUpload/sound/
# Video file upload and save directory
videoPath = fileUpload/video/
# uEditor uploads files to save directory (including pictures, videos, audio, text, etc.)
ueditor = fileUpload/ueditor/
Copy the code
- Add upload.properties to the Spring startup configuration file application.xml for later Controller access
<! -- Import database configuration file -->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:config.properties</value>
<value>classpath:redis.properties</value>
<value>classpath:upload.properties</value>
</list>
</property>
</bean>
Copy the code
4. Write the tool class uploadUtil.java
package cn.lega.common.util;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
public class UploadUtil {
/** * Upload file **@param request
* @param response
* @param* serverPath server address: (http://172.16.5.102:8090/)@paramPath File path (excluding server address: upload/) *@return* /
public static String upload(Client client, MultipartFile file, HttpServletRequest request, HttpServletResponse response, String serverPath, String path) {
// File name generation policy (datetime +uuid)
UUID uuid = UUID.randomUUID();
Date d = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String formatDate = format.format(d);
// Get the extension of the file
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
/ / file name
String fileName = formatDate + "-" + uuid + "." + extension;
// Relative path
String relaPath = path + fileName;
// String a = serverPath + path.substring(0, path.lastIndexOf("/"));
// File file2 = new File(a);
// if (! file2.exists()) {
// boolean mkdirs = file2.mkdirs();
// System.out.println(mkdirs);
/ /}
// The URL of another Tomcat (real path)
String realPath = serverPath + relaPath;
// Set the request path
// WebResource resource = client.resource(realPath);
// Send start post get put
// try {
// resource.put(String.class, file.getBytes());
// return fileName + ";" + relaPath + ";" + realPath;
// } catch (IOException e) {
// e.printStackTrace();
// return "";
/ /}
// User directory /root/fileupload/ueditor
String userDir = System.getProperty("user.home");
String ueditorUploadPath = userDir + File.separator + path;
File file2 = new File(ueditorUploadPath);
if(! file2.exists()) { file2.mkdirs(); } String newFilePath = ueditorUploadPath + fileName;// Save it locally
File file3 = new File(newFilePath);
try {
FileCopyUtils.copy(file.getBytes(), file3);
return fileName + ";" + relaPath + ";" + realPath;
} catch (IOException e) {
e.printStackTrace();
return ""; }}public static String delete(String filePath) {
try {
Client client = new Client();
WebResource resource = client.resource(filePath);
resource.delete();
return "y";
} catch (Exception e) {
e.printStackTrace();
return "n"; }}}Copy the code
5. Write the Controller class UEditorController.java to provide the upload interface for the front-end
package cn.lega.common.controller;
import cn.lega.common.baidu.ueditor.ActionEnter;
import cn.lega.common.util.ResponseUtils;
import cn.lega.common.util.StrUtils;
import cn.lega.common.util.UploadUtil;
import cn.lega.common.web.BaseController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.jersey.api.client.Client;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
/** * to handle requests related to the uEditor plug-in **@author silianpan
*/
@RestController
@CrossOrigin
@RequestMapping("/common/ueditor")
public class UeditorController extends BaseController {
// Background image save address
@Value("#{configProperties['ueditor']}")
private String ueditor;
@Value("#{configProperties['uploadHost']}")
private String uploadHost; // Project host path
/** * UEditor file upload (upload to external server) **@param request
* @param response
* @param action
*/
@ResponseBody
@RequestMapping(value = "/ueditorUpload.do", method = {RequestMethod.GET, RequestMethod.POST})
public void editorUpload(HttpServletRequest request, HttpServletResponse response, String action) {
response.setContentType("application/json");
String rootPath = request.getSession().getServletContext().getRealPath("/");
try {
if ("config".equals(action)) { // If it is initialized
String exec = new ActionEnter(request, rootPath).exec();
PrintWriter writer = response.getWriter();
writer.write(exec);
writer.flush();
writer.close();
} else if ("uploadimage".equals(action) || "uploadvideo".equals(action) || "uploadfile".equals(action)) { // Upload pictures, videos and other files
try {
MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
MultipartHttpServletRequest Murequest = resolver.resolveMultipart(request);
Map<String, MultipartFile> files = Murequest.getFileMap();// Get the file map object
// instantiate jersey
Client client = new Client();
for (MultipartFile pic : files.values()) {
JSONObject jo = new JSONObject();
long size = pic.getSize(); // File size
String originalFilename = pic.getOriginalFilename(); // The original file name
if (StrUtils.isEmpty(uploadHost) || uploadHost.equals("default")) {
uploadHost = System.getProperty("user.home") + File.separator;
}
String uploadInfo = UploadUtil.upload(client, pic, request, response, uploadHost, ueditor);
if (!"".equals(uploadInfo)) { // If the upload succeeds
String[] infoList = uploadInfo.split(";");
jo.put("state"."SUCCESS");
jo.put("original", originalFilename);// The original file name
jo.put("size", size); // File size
jo.put("title", infoList[1]); // Random, which represents the text displayed when the mouse moves over the picture
jo.put("type", FilenameUtils.getExtension(pic.getOriginalFilename())); // File name extension
jo.put("url", infoList[2]);/ / url field said here is that the upload picture in picture server after complete address (http://ip: port / / * * * * * *. * * * / JPG)
} else { // If upload fails} ResponseUtils.renderJson(response, jo.toString()); }}catch(Exception e) { e.printStackTrace(); }}}catch (Exception e) {
}
}
// @RequestMapping(value = "/exec")
// public void config(HttpServletRequest request, HttpServletResponse response) {
// // response.setContentType("application/json");
// String rootPath = request.getSession().getServletContext().getRealPath("/");
// response.setHeader("Content-Type" , "text/html");
// try {
// String exec = new ActionEnter(request, rootPath).exec();
// PrintWriter writer = response.getWriter();
// writer.write(exec);
// writer.flush();
// writer.close();
// } catch (IOException e) {
// e.printStackTrace();
/ /}
/ /}
@RequestMapping(value = "/exec")
@ResponseBody
public String exec(HttpServletRequest request) throws UnsupportedEncodingException {
request.setCharacterEncoding("utf-8");
String rootPath = request.getSession().getServletContext().getRealPath("/");
return new ActionEnter(request, rootPath).exec();
}
@RequestMapping("/ueconfig")
public void getUEConfig(HttpServletRequest request, HttpServletResponse response) {
org.springframework.core.io.Resource res = new ClassPathResource("ueditorConfig.json");
InputStream is = null;
response.setHeader("Content-Type"."text/html");
try {
is = new FileInputStream(res.getFile());
StringBuffer sb = new StringBuffer();
byte[] b = new byte[1024];
int length = 0;
while (-1! = (length = is.read(b))) { sb.append(new String(b, 0, length, "utf-8"));
}
String result = sb.toString().replaceAll("/\\*(.|[\\r\\n])*? \ \ * /"."");
JSONObject json = JSON.parseObject(result);
PrintWriter out = response.getWriter();
out.print(json.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch(IOException e) { e.printStackTrace(); }}}}Copy the code
Vue front-end integration
1. Decompress the JSP version and copy it to the static directory of the Vue front-end project
2. Configure front-end constants
// Static directory
export const STATIC_PATH = process.env.NODE_ENV === 'production' ? './static/' : '/static/'
// UEditor service path, corresponding to the uEditorController.java upload interface
export const UEDITOR_SERVER = API_BASEURL + '/common/ueditor/ueditorUpload.do'
Copy the code
3. Install vue-ueditor-wrap
npm install vue-ueditor-wrap
or
yarn add vue-ueditor-wrap
Copy the code
4. Write components
<template> <div> <component style="width:100%! important" :is="currentViewComp" transition="fade" transition-mode="out-in" :config="ueditorConfig" v-model="formData[item.prop]" :destroy="true" @ready="ueReady"> </component> </div> </template> <script> import VueUeditorWrap from 'vue-ueditor-wrap' import { STATIC_PATH, UEDITOR_SERVER } from '@/config' export default { data() { return { currentViewComp: null, ueditorConfig: { serverUrl: UEDITOR_SERVER, UEDITOR_HOME_URL: STATIC_PATH + 'ueditor1_4_3_3/', initialContent: '', initialFrameHeight: 400, initialFrameWidth: '100%', autoHeightEnabled: false } } }, mounted() { this.currentViewComp = VueUeditorWrap }, destroyed() { this.currentViewComp = null }, methods: { ueReady(editorInstance) { this.$nextTick(() => { editorInstance.setContent('') }) } } } </script>Copy the code
Tomcat File Service
Configure tomcat/conf/server.xml and add the following code
Port =8090 File access service port docBase=”/home/” File storage directory
<Service name="fileUpload">
<! -- Assign port 8089 -->
<! -- <Connector port="8090" protocol="HTTP/1.1" connectionTimeout="20000" URIEncoding="GBK" redirectPort="8443" />
<Connector port="8090" protocol="HTTP / 1.1" connectionTimeout="20000" redirectPort="8443" />
<Engine name="fileUpload" defaultHost="localhost">
<! --name is the project access address. The configured access is http://localhost:8080 appBase. Configure the tomcat wabapps directory -->
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
<! -- Resource address -->
<Context path="" docBase="/home/" debug="0" reloadable="false"/>
</Host>
</Engine>
</Service>
Copy the code
At this point, the work is done
Spring+Vue integrates UEditor rich text to upload pictures