https://ueditor.baidu.com/web...
下載完整源碼和JSP版本javascript
jsp目錄下java源碼
集成spring mvc後端
#host地址 host=http://localhost:8081/ssm_project #文件上傳服務器地址(ip+端口) uploadHost=http://localhost:8090/ #普通圖片上傳保存目錄 imagePath = fileUpload/image/ #系統用戶頭像上傳保存目錄 headImgPath = fileUpload/image/headImg/ #系統用戶默認頭像 sysUserDefImg = sysUser-default.jpg #文本文件上傳保存目錄 documentPath = fileUpload/document/ #音頻文件上傳保存目錄 soundPath = fileUpload/sound/ #視頻文件上傳保存目錄 videoPath = fileUpload/video/ #ueditor編輯器上傳文件保存目錄(包括圖片、視頻、音頻、文本等文件) ueditor = fileUpload/ueditor/
<!-- 引入數據庫配置文件 --> <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>
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 { /** * 上傳文件 * * @param request * @param response * @param serverPath 服務器地址:(http://172.16.5.102:8090/) * @param path 文件路徑(不包含服務器地址:upload/) * @return */ public static String upload(Client client, MultipartFile file, HttpServletRequest request, HttpServletResponse response, String serverPath, String path) { // 文件名稱生成策略(日期時間+uuid ) UUID uuid = UUID.randomUUID(); Date d = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String formatDate = format.format(d); // 獲取文件的擴展名 String extension = FilenameUtils.getExtension(file.getOriginalFilename()); // 文件名 String fileName = formatDate + "-" + uuid + "." + extension; //相對路徑 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); // } // 另外一臺tomcat的URL(真實路徑) String realPath = serverPath + relaPath; // 設置請求路徑 // WebResource resource = client.resource(realPath); // 發送開始post get put(基於put提交) // try { // resource.put(String.class, file.getBytes()); // return fileName + ";" + relaPath + ";" + realPath; // } catch (IOException e) { // e.printStackTrace(); // return ""; // } // 用戶目錄/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; // 保存在本地 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"; } } }
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; /** * 用於處理關於ueditor插件相關的請求 * * @author silianpan */ @RestController @CrossOrigin @RequestMapping("/common/ueditor") public class UeditorController extends BaseController { // 後臺圖片保存地址 @Value("#{configProperties['ueditor']}") private String ueditor; @Value("#{configProperties['uploadHost']}") private String uploadHost; //項目host路徑 /** * ueditor文件上傳(上傳到外部服務器) * * @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)) { // 若是是初始化 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)) { // 若是是上傳圖片、視頻、和其餘文件 try { MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext()); MultipartHttpServletRequest Murequest = resolver.resolveMultipart(request); Map<String, MultipartFile> files = Murequest.getFileMap();// 獲得文件map對象 // 實例化一個jersey Client client = new Client(); for (MultipartFile pic : files.values()) { JSONObject jo = new JSONObject(); long size = pic.getSize(); // 文件大小 String originalFilename = pic.getOriginalFilename(); // 原來的文件名 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)) { // 若是上傳成功 String[] infoList = uploadInfo.split(";"); jo.put("state", "SUCCESS"); jo.put("original", originalFilename);//原來的文件名 jo.put("size", size); // 文件大小 jo.put("title", infoList[1]); // 隨意,表明的是鼠標通過圖片時顯示的文字 jo.put("type", FilenameUtils.getExtension(pic.getOriginalFilename())); // 文件後綴名 jo.put("url", infoList[2]);// 這裏的url字段表示的是上傳後的圖片在圖片服務器的完整地址(http://ip:端口/***/***/***.jpg) } else { // 若是上傳失敗 } 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(); } } } }
// 靜態目錄 export const STATIC_PATH = process.env.NODE_ENV === 'production' ? './static/' : '/static/' // UEditor服務路徑,對應UeditorController.java上傳接口 export const UEDITOR_SERVER = API_BASEURL + '/common/ueditor/ueditorUpload.do'
npm install vue-ueditor-wrap or yarn add vue-ueditor-wrap
<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>
配置tomcat/conf/server.xml,添加以下代碼php
port=8090 文件訪問服務端口
docBase="/home/" 文件存儲目錄
<Service name="fileUpload"> <!--分配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爲項目訪問地址 此配置的訪問爲http://localhost:8080 appBase配置tomcat下wabapps下的路徑--> <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"> <!--資源地址--> <Context path="" docBase="/home/" debug="0" reloadable="false"/> </Host> </Engine> </Service>
轉載請註明:思戀 » Spring+Vue整合UEditor富文本實現圖片附件上傳html