栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring+Vue整合UEditor富文本实现图片附件上传的方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring+Vue整合UEditor富文本实现图片附件上传的方法

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

放到java项目的resource目录下,在这里是ueditorConfig.json

配置config.json文件名称,这里是ueditorConfig.json

3. 项目常量配置文件新建upload.properties,也放在resouce目录下,文件内容如下:

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

将upload.properties添加到Spring启动配置文件application.xml中,以便后面Controller访问



  
    
      classpath:config.properties
      classpath:redis.properties
      classpath:upload.properties
    
  

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

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;


@RestController
@CrossOrigin
@RequestMapping("/common/ueditor")
public class UeditorController extends baseController {

  // 后台图片保存地址
  @Value("#{configProperties['ueditor']}")
  private String ueditor;

  @Value("#{configProperties['uploadHost']}")
  private String uploadHost;  //项目host路径

  
  @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 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:端口***", "");
      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前端项目static目录中

2. 前端常量配置

// 静态目录
export const STATIC_PATH = process.env.NODE_ENV === 'production' ? './static/' : '/static/'
// UEditor服务路径,对应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. 编写组件


至此,大功告成~

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/137674.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号