Spring+Vue integrates UEditor rich text to upload image attachments

Keywords: Java JSON Vue JSP

Download UEditor

https://ueditor.baidu.com/web...

Download the full source and JSP versions

Spring backend integration

1. Decompress the complete source code, copy the java source code under the jsp directory to the spring mvc backend.

java source code in jsp directory

Integrating spring mvc backend

2. Configure config.json

  • Unzip JSP version
  • Copy config.json under jsp directory

  • Put it in the resource directory of the java project. Here is ueditorConfig.json

  • Configuration config.json file name, here is ueditorConfig.json

3. Project constant configuration file

  • Create upload.properties and put it in the resource directory. The file contents are as follows:
#host address
host=http://localhost:8081/ssm_project
#File upload server address (ip + port)
uploadHost=http://localhost:8090/
#General picture upload and save directory
imagePath = fileUpload/image/
#Upload and save the system user's Avatar
headImgPath = fileUpload/image/headImg/
#Default image of system user
sysUserDefImg = sysUser-default.jpg
#Upload and save directory of text file
documentPath = fileUpload/document/
#Audio file upload and save directory
soundPath = fileUpload/sound/
#Video file upload and save directory
videoPath = fileUpload/video/
#ueditor editor upload file save directory (including picture, video, audio, text and other files)
ueditor = fileUpload/ueditor/
  • Add upload.properties to the Spring startup configuration file application.xml for later Controller access
<!-- Import database profile -->
<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. 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 files
     *
     * @param request
     * @param response
     * @param serverPath Server address: (http://172.16.5.102:8090/)
     * @param path       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 strategy (datetime + uuid)
        UUID uuid = UUID.randomUUID();
        Date d = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String formatDate = format.format(d);
        // Get file extension
        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);
//        }

        // URL of another tomcat (real path)
        String realPath = serverPath + relaPath;
        // Set request path
//        WebResource resource = client.resource(realPath);

        // Send start post get put (submit based on 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 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";
        }
    }
}

5. Write Controller class UeditorController.java to provide 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;

/**
 * For processing requests related to the ueditor plug-in
 *
 * @author silianpan
 */
@RestController
@CrossOrigin
@RequestMapping("/common/ueditor")
public class UeditorController extends BaseController {

    // Background image storage 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's initialization
                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)) {    // If uploading 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 file map object
                    // Instantiate a jersey
                    Client client = new Client();

                    for (MultipartFile pic : files.values()) {
                        JSONObject jo = new JSONObject();
                        long size = pic.getSize();    // file size
                        String originalFilename = pic.getOriginalFilename();  // Original filename
                        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 is successful
                            String[] infoList = uploadInfo.split(";");
                            jo.put("state", "SUCCESS");
                            jo.put("original", originalFilename);//Original filename
                            jo.put("size", size); // file size
                            jo.put("title", infoList[1]); // At will, it represents the text displayed when the mouse passes the picture
                            jo.put("type", FilenameUtils.getExtension(pic.getOriginalFilename())); // File suffix
                            jo.put("url", infoList[2]);// The url field here represents the full address of the uploaded image on the image server (http://ip: port / *** / * * *. jpg)
                        } else {    // If the 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();
            }
        }
    }
}

Vue front end integration

1. Extract the jsp version and copy it to the static directory of the Vue front-end project.

2. Front end constant configuration

// Static directory
export const STATIC_PATH = process.env.NODE_ENV === 'production' ? './static/' : '/static/'
// UEditor service path, corresponding to UeditorController.java upload interface
export const UEDITOR_SERVER = API_BASEURL + '/common/ueditor/ueditorUpload.do'

3. Install the plug-in Vue ueditor wrap

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

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>

So far, it's done.~

Please indicate: Spring+Vue integrates UEditor rich text to upload image attachments

Posted by llandudno on Sat, 02 Nov 2019 21:31:18 -0700