最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring+Vue整合UEditor富文本實(shí)現(xiàn)圖片附件上傳的方法

 更新時(shí)間:2019年07月10日 08:27:26   作者:silianpan  
這篇文章主要介紹了Spring+Vue整合UEditor富文本實(shí)現(xiàn)圖片附件上傳的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

下載UEditor

https://ueditor.baidu.com/website/download.html

下載完整源碼和JSP版本

Spring后端集成

1. 解壓完整源碼,拷貝jsp目錄下的java源碼,到spring mvc后端

jsp目錄下java源碼

集成spring mvc后端

2. 配置config.json

  • 解壓JSP版本
  • 拷貝jsp目錄下config.json

放到j(luò)ava項(xiàng)目的resource目錄下,在這里是ueditorConfig.json

配置config.json文件名稱,這里是ueditorConfig.json

3. 項(xiàng)目常量配置文件新建upload.properties,也放在resouce目錄下,文件內(nèi)容如下:

#host地址
host=http://localhost:8081/ssm_project
#文件上傳服務(wù)器地址(ip+端口)
uploadHost=http://localhost:8090/
#普通圖片上傳保存目錄
imagePath = fileUpload/image/
#系統(tǒng)用戶頭像上傳保存目錄
headImgPath = fileUpload/image/headImg/
#系統(tǒng)用戶默認(rèn)頭像
sysUserDefImg = sysUser-default.jpg
#文本文件上傳保存目錄
documentPath = fileUpload/document/
#音頻文件上傳保存目錄
soundPath = fileUpload/sound/
#視頻文件上傳保存目錄
videoPath = fileUpload/video/
#ueditor編輯器上傳文件保存目錄(包括圖片、視頻、音頻、文本等文件)
ueditor = fileUpload/ueditor/

將upload.properties添加到Spring啟動(dòng)配置文件application.xml中,以便后面Controller訪問

<!-- 引入數(shù)據(jù)庫配置文件 -->
<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>

4. 編寫工具類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 {
  /**
   * 上傳文件
   *
   * @param request
   * @param response
   * @param serverPath 服務(wù)器地址:(http://172.16.5.102:8090/)
   * @param path    文件路徑(不包含服務(wù)器地址:upload/)
   * @return
   */
  public static String upload(Client client, MultipartFile file, HttpServletRequest request, HttpServletResponse response, String serverPath, String path) {
    // 文件名稱生成策略(日期時(shí)間+uuid )
    UUID uuid = UUID.randomUUID();
    Date d = new Date();
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    String formatDate = format.format(d);
    // 獲取文件的擴(kuò)展名
    String extension = FilenameUtils.getExtension(file.getOriginalFilename());
    // 文件名
    String fileName = formatDate + "-" + uuid + "." + extension;
    //相對(duì)路徑
    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);
//    }

    // 另一臺(tái)tomcat的URL(真實(shí)路徑)
    String realPath = serverPath + relaPath;
    // 設(shè)置請(qǐng)求路徑
//    WebResource resource = client.resource(realPath);

    // 發(fā)送開始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";
    }
  }
}

5. 編寫Controller類UeditorController.java,為前端提供上傳接口

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;

/**
 * 用于處理關(guān)于ueditor插件相關(guān)的請(qǐng)求
 *
 * @author silianpan
 */
@RestController
@CrossOrigin
@RequestMapping("/common/ueditor")
public class UeditorController extends BaseController {

  // 后臺(tái)圖片保存地址
  @Value("#{configProperties['ueditor']}")
  private String ueditor;

  @Value("#{configProperties['uploadHost']}")
  private String uploadHost;  //項(xiàng)目host路徑

  /**
   * ueditor文件上傳(上傳到外部服務(wù)器)
   *
   * @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對(duì)象
          // 實(shí)例化一個(gè)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]); // 隨意,代表的是鼠標(biāo)經(jīng)過圖片時(shí)顯示的文字
              jo.put("type", FilenameUtils.getExtension(pic.getOriginalFilename())); // 文件后綴名
              jo.put("url", infoList[2]);// 這里的url字段表示的是上傳后的圖片在圖片服務(wù)器的完整地址(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();
      }
    }
  }
}

Vue前端集成

1. 解壓jsp版本,拷貝到Vue前端項(xiàng)目static目錄中

2. 前端常量配置

// 靜態(tài)目錄
export const STATIC_PATH = process.env.NODE_ENV === 'production' ? './static/' : '/static/'
// UEditor服務(wù)路徑,對(duì)應(yīng)UeditorController.java上傳接口
export const UEDITOR_SERVER = API_BASEURL + '/common/ueditor/ueditorUpload.do'

3. 安裝插件vue-ueditor-wrap

npm install vue-ueditor-wrap
or
yarn add vue-ueditor-wrap

4. 編寫組件

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

至此,大功告成~

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 優(yōu)惠券優(yōu)惠的思路以及實(shí)踐

    優(yōu)惠券優(yōu)惠的思路以及實(shí)踐

    本文主要介紹了優(yōu)惠券優(yōu)惠的思路以及實(shí)踐。具有很好的參考價(jià)值,下面跟著小編一起來看下吧
    2017-02-02
  • SpringCloud  OpenFeign 參數(shù)傳遞和響應(yīng)處理的詳細(xì)步驟

    SpringCloud  OpenFeign 參數(shù)傳遞和響應(yīng)處理的詳細(xì)步驟

    本文給大家講解SpringCloud  OpenFeign 參數(shù)傳遞和響應(yīng)處理的詳細(xì)步驟,本文給大家講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2024-02-02
  • FasfDFS整合Java實(shí)現(xiàn)文件上傳下載功能實(shí)例詳解

    FasfDFS整合Java實(shí)現(xiàn)文件上傳下載功能實(shí)例詳解

    這篇文章主要介紹了FasfDFS整合Java實(shí)現(xiàn)文件上傳下載功能實(shí)例詳解,需要的朋友可以參考下
    2017-08-08
  • Java?Lambda表達(dá)式語法及用法示例

    Java?Lambda表達(dá)式語法及用法示例

    這篇文章主要給大家介紹了關(guān)于Java?Lambda表達(dá)式語法及用法的相關(guān)資料,lambda表達(dá)式是JAVA8中提供的一種新的特性,它支持Java也能進(jìn)行簡單的"函數(shù)式編程",文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-10-10
  • Java中的FileWriter用法詳解與實(shí)戰(zhàn)記錄

    Java中的FileWriter用法詳解與實(shí)戰(zhàn)記錄

    這篇文章主要給大家介紹了關(guān)于Java中FileWriter用法的相關(guān)資料,包括寫入字符數(shù)據(jù)到文件、字符數(shù)組和部分字符寫入、配合BufferedWriter使用等方法,同時(shí)也解釋了其與OutputStreamWriter,BufferedWriter的異同特性,適合簡單的文件寫入操作,需要的朋友可以參考下
    2024-10-10
  • java怎么設(shè)置代理ip實(shí)現(xiàn)高效網(wǎng)絡(luò)請(qǐng)求

    java怎么設(shè)置代理ip實(shí)現(xiàn)高效網(wǎng)絡(luò)請(qǐng)求

    無論是在爬蟲、API調(diào)用還是網(wǎng)絡(luò)測試中,代理IP的使用都變得愈發(fā)重要,本文我們主要來介紹一下如何在Java中設(shè)置代理IP實(shí)現(xiàn)高效網(wǎng)絡(luò)請(qǐng)求吧
    2024-11-11
  • 深入剖析Java ArrayQueue(JDK)的源碼

    深入剖析Java ArrayQueue(JDK)的源碼

    本篇文章主要給大家介紹一個(gè)比較簡單的JDK為我們提供的容器ArrayQueue,這個(gè)容器主要是用數(shù)組實(shí)現(xiàn)的一個(gè)單向隊(duì)列,整體的結(jié)構(gòu)相對(duì)其他容器來說就比較簡單了,感興趣的可以了解一下
    2022-08-08
  • SpringMVC如何自定義響應(yīng)的HTTP狀態(tài)碼

    SpringMVC如何自定義響應(yīng)的HTTP狀態(tài)碼

    這篇文章主要介紹了SpringMVC如何自定義響應(yīng)的HTTP狀態(tài)碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • Java規(guī)則引擎Easy Rules的使用介紹

    Java規(guī)則引擎Easy Rules的使用介紹

    這篇文章主要介紹了Java規(guī)則引擎Easy Rules的使用介紹,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • 尋找二叉樹最遠(yuǎn)的葉子結(jié)點(diǎn)(實(shí)例講解)

    尋找二叉樹最遠(yuǎn)的葉子結(jié)點(diǎn)(實(shí)例講解)

    下面小編就為大家分享一篇尋找二叉樹最遠(yuǎn)的葉子結(jié)點(diǎn)的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2017-12-12

最新評(píng)論

武平县| 科尔| 梧州市| 兴义市| 厦门市| 郓城县| 米易县| 兰考县| 鄂尔多斯市| 沂水县| 延津县| 池州市| 鹤壁市| 平湖市| 滨海县| 抚顺市| 屯门区| 辽阳县| 呼玛县| 舟山市| 沙雅县| 临清市| 邯郸市| 永宁县| 分宜县| 双柏县| 永昌县| 兴隆县| 资溪县| 江口县| 临江市| 鄢陵县| 南平市| 陆川县| 马公市| 吉木萨尔县| 三台县| 迁西县| 宿迁市| 沙田区| 崇左市|