Ueditor與SpringMVC整合

目的

本文旨在整合百度前端富文本Ueditor與SpringMVC,使用Spring Controller做爲Ueditor的後端,提供上傳圖片等後臺相關的功能,即便用SpringMVC替換官方提供的JSP後臺方式。前端

步驟

  • 建立web工程,本文以maven進行建立和管理,最終目錄結構以下:
    圖片描述
  • 建立Ueditor統一後臺Controller服務java

    import org.apache.commons.io.FileUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.util.ResourceUtils;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    @Controller
    @RequestMapping("/ued")
    public class UeditorController{
        
        @RequestMapping("/serverUrl")
        @ResponseBody
        public Object test(HttpServletRequest request,
                           @RequestParam(value = "action") String action, 
                           @RequestParam(value = "upfile", required = false) MultipartFile file) throws Exception {
           switch (action) {
               case "config": // 加載返回ueditor配置文件conf/config.json
                   return getConfig();
               case "uploadimage": // 上傳圖片
                   return uploadImage(request, file);
               case "uploadvideo": // 上傳視頻
                   return "視頻處理方法";
               case "uploadfile": // 上傳文件
                   return "文件處理方法";
               default:
                   return "無效action";
            }
        }
       
        private String getConfig() throws Exception {
            File file = ResourceUtils.getFile("classpath:conf/config.json");
            String json = FileUtils.readFileToString(file, "utf-8");
            return json;
        }
        
        private Map<String, Object> uploadImage(HttpServletRequest request, MultipartFile file) {
            
            String state = "SUCCESS";
            String savedDir = request.getSession().getServletContext().getRealPath("upload");
            String filename = file.getOriginalFilename();
            File filepath = new File(savedDir,filename);
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            // 寫到服務器路徑下,可擴展,好比上傳到雲端或文件服務器
            file.transferTo(new File(savedDir + File.separator + filename));
            String uploadHttpUrl = "http://localhost:8083/upload"+ File.separator + filename;
            return resultMap(file, state, uploadHttpUrl);
        }
        
        private Map<String, Object> resultMap(MultipartFile file, String state, String uploadHttpUrl) {
            Map<String, Object> resMap = new HashMap<String, Object>();
            resMap.put("state", state);  //"SUCCESS" 表示成功
            resMap.put("title", file.getOriginalFilename());
            resMap.put("original", file.getOriginalFilename());
            resMap.put("type", file.getContentType());
            resMap.put("size", file.getSize());
            resMap.put("url", uploadHttpUrl);
            return resMap;
        }
       
    }
  • 資源加載幫助類web

    import org.springframework.util.Assert;
     import org.springframework.util.ClassUtils;
     import org.springframework.util.StringUtils;
     import java.io.File;
     import java.io.FileNotFoundException;
     import java.net.MalformedURLException;
     import java.net.URI;
     import java.net.URISyntaxException;
     import java.net.URL;
     public class ResourceUtils{
         public static File getFile(String resourceLocation) throws FileNotFoundException {
             Assert.notNull(resourceLocation, "Resource location must not be null");
             if (resourceLocation.startsWith("classpath:")) {
                 String path = resourceLocation.substring("classpath:".length());
                 String description = "class path resource [" + path + "]";
                 ClassLoader cl = ClassUtils.getDefaultClassLoader();
                 URL url = cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path);
                 if (url == null) {
                     throw new FileNotFoundException(description + " cannot be resolved to absolute file path because it does not exist");
                     
                 }else{
                     return getFile(url, description);
                 }
             }else{
                 try {
                     return getFile(new URL(resourceLocation));
                 }catch (MalformedURLException var5) {
                     return new File(resourceLocation);
                 }
             }
         }
         public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
             Assert.notNull(resourceUrl, "Resource URL must not be null");
             if (!"file".equals(resourceUrl.getProtocol())) {
                 throw new FileNotFoundException(description + " cannot be resolved to absolute file path because it does not reside in the file system: " + resourceUrl);
             }else{
                 try {
                     return new File(toURI(resourceUrl).getSchemeSpecificPart());
                 } catch (URISyntaxException var3) {
                     return new File(resourceUrl.getFile());
                 }
             }
         }
         public static URI toURI(URL url) throws URISyntaxException {
             return toURI(url.toString());
         }
         public static URI toURI(String location) throws URISyntaxException {
             return new URI(StringUtils.replace(location, " ", "%20"));
         }
         public static File getFile(URL resourceUrl) throws FileNotFoundException {
             return getFile(resourceUrl, "URL");
         }
     }
  • 配置ueditor.config.js

    把文件中的serverUrl: URL + "jsp/controller.jsp",修改成serverUrl: "/ued/serverUrl" 便可。spring

效果

圖片描述

圖片描述

相關文章
相關標籤/搜索