ueditor上传图片视频Java-前后端分离

1、本人下载版本号是:1.4.3.3 完整源码,后台需要改的东西。

(1)完整版本里有源码:ueditor-1.4.3.3\ueditor-1.4.3.3\jsp\src,下面所有源码复制到项目src下面。

(2)找到BinaryUploader类用以下代码替换。

package com.baidu.ueditor.upload;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class BinaryUploader {

   public static final State save(HttpServletRequest request,
                           Map<String, Object> conf) {
      if (!ServletFileUpload.isMultipartContent(request)) {
         return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
      }
      try {
         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
         MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());
         if(multipartFile==null){
            return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
         }

         String savePath = (String) conf.get("savePath");
         //String originFileName = fileStream.getName();
         String originFileName = multipartFile.getOriginalFilename();
         String suffix = FileType.getSuffixByFilename(originFileName);
         originFileName = originFileName.substring(0,
               originFileName.length() - suffix.length());
         savePath = savePath + suffix;
         long maxSize = ((Long) conf.get("maxSize")).longValue();
         if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
            return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
         }
         savePath = PathFormat.parse(savePath, originFileName);
         //String physicalPath = (String) conf.get("rootPath") + savePath;
         String physicalPath = (String)conf.get("basePath")+savePath;
               //InputStream is = fileStream.openStream();
         InputStream is = multipartFile.getInputStream();
         State storageState = StorageManager.saveFileByInputStream(is,
               physicalPath, maxSize);
         is.close();

         if (storageState.isSuccess()) {
            storageState.putInfo("url", PathFormat.format(savePath));
            storageState.putInfo("type", suffix);
            storageState.putInfo("original", originFileName + suffix);
         }
         return storageState;
      } catch (IOException e) {
      }
      return new BaseState(false, AppInfo.IO_ERROR);
   }

   private static boolean validType(String type, String[] allowTypes) {
      List<String> list = Arrays.asList(allowTypes);
      return list.contains(type);
   }
}

(3)把config.json移到resources下面。

(4)找到ConfigManager类初始化方法,用以下替换initEnv。防止后台从resources下面加载config.json出错

private void initEnv () throws FileNotFoundException, IOException {
   
   File file = new File( this.originalPath );
   
   if ( !file.isAbsolute() ) {
      file = new File( file.getAbsolutePath() );
   }
   
   this.parentPath = file.getParent();
   
   //String configContent = this.readFile( this.getConfigPath() );
   String configContent = this.filter(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("config.json")));

   try{
      JSONObject jsonConfig = new JSONObject( configContent );
      this.jsonConfig = jsonConfig;
   } catch ( Exception e ) {
      this.jsonConfig = null;
   }
   try{
      JSONObject jsonConfig = new JSONObject( configContent );
      this.jsonConfig = jsonConfig;
   } catch ( Exception e ) {
      this.jsonConfig = null;
   }
   
}

还有getConfig ,把basePath加入conf中,为config.json做铺垫。

public Map<String, Object> getConfig ( int type ) {
   
   Map<String, Object> conf = new HashMap<String, Object>();
   String savePath = null;
   
   switch ( type ) {
   
      case ActionMap.UPLOAD_FILE:
         conf.put( "isBase64", "false" );
         conf.put( "maxSize", this.jsonConfig.getLong( "fileMaxSize" ) );
         conf.put( "allowFiles", this.getArray( "fileAllowFiles" ) );
         conf.put( "fieldName", this.jsonConfig.getString( "fileFieldName" ) );
         savePath = this.jsonConfig.getString( "filePathFormat" );
         break;
         
      case ActionMap.UPLOAD_IMAGE:
         conf.put( "isBase64", "false" );
         conf.put( "maxSize", this.jsonConfig.getLong( "imageMaxSize" ) );
         conf.put( "allowFiles", this.getArray( "imageAllowFiles" ) );
         conf.put( "fieldName", this.jsonConfig.getString( "imageFieldName" ) );
         savePath = this.jsonConfig.getString( "imagePathFormat" );
         break;
         
      case ActionMap.UPLOAD_VIDEO:
         conf.put( "maxSize", this.jsonConfig.getLong( "videoMaxSize" ) );
         conf.put( "allowFiles", this.getArray( "videoAllowFiles" ) );
         conf.put( "fieldName", this.jsonConfig.getString( "videoFieldName" ) );
         savePath = this.jsonConfig.getString( "videoPathFormat" );
         break;
         
      case ActionMap.UPLOAD_SCRAWL:
         conf.put( "filename", ConfigManager.SCRAWL_FILE_NAME );
         conf.put( "maxSize", this.jsonConfig.getLong( "scrawlMaxSize" ) );
         conf.put( "fieldName", this.jsonConfig.getString( "scrawlFieldName" ) );
         conf.put( "isBase64", "true" );
         savePath = this.jsonConfig.getString( "scrawlPathFormat" );
         break;
         
      case ActionMap.CATCH_IMAGE:
         conf.put( "filename", ConfigManager.REMOTE_FILE_NAME );
         conf.put( "filter", this.getArray( "catcherLocalDomain" ) );
         conf.put( "maxSize", this.jsonConfig.getLong( "catcherMaxSize" ) );
         conf.put( "allowFiles", this.getArray( "catcherAllowFiles" ) );
         conf.put( "fieldName", this.jsonConfig.getString( "catcherFieldName" ) + "[]" );
         savePath = this.jsonConfig.getString( "catcherPathFormat" );
         break;
         
      case ActionMap.LIST_IMAGE:
         conf.put( "allowFiles", this.getArray( "imageManagerAllowFiles" ) );
         conf.put( "dir", this.jsonConfig.getString( "imageManagerListPath" ) );
         conf.put( "count", this.jsonConfig.getInt( "imageManagerListSize" ) );
         break;
         
      case ActionMap.LIST_FILE:
         conf.put( "allowFiles", this.getArray( "fileManagerAllowFiles" ) );
         conf.put( "dir", this.jsonConfig.getString( "fileManagerListPath" ) );
         conf.put( "count", this.jsonConfig.getInt( "fileManagerListSize" ) );
         break;
         
   }
   //将basePath塞进conf
   conf.put("basePath",this.jsonConfig.getString("basePath"));
   conf.put( "savePath", savePath );
   conf.put( "rootPath", this.rootPath );
   
   return conf;
   
}

(5)自定义控制层类替换controller.jsp,代码如下

package com.foodo.cloud.admin.modules.web.controller;

import com.baidu.ueditor.ActionEnter;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName FileUploadController
 * @Description TODO
 * @Author zhaodaolin
 * @Date 2018/7/26 16:01
 * @Version 1.0
 */
@RestController
@RequestMapping("web/fileUpload")
public class FileUploadController {
    //处理文件上传
    @RequestMapping(value="/upload", method = RequestMethod.POST)
    public Map<String, Object> uploadimage(@RequestParam("file") MultipartFile upfile){
        Map<String, Object> params = new HashMap<String, Object>();
        try{

            String basePath = "";//物理路径
            String visitUrl = "";//服务器路径
            //为了方便的上传和管理图片,我在服务器中配置了专门的图片存取路径。即在tomcat
            //的server.xml中添加一句 <Context docBase="d:/assets" path="/assets" reloadable="true"/>
            String ext;
            String name = upfile.getOriginalFilename();
            if(name == null || "".equals(name) || !name.contains("."))
                ext = "";
            else{
                ext = name.substring(name.lastIndexOf(".")+1);
            }
            String fileName = String.valueOf(System.currentTimeMillis()).concat("_").concat(String.valueOf(RandomUtils.nextInt(0, 6))).concat(".").concat(ext);
            StringBuilder sb = new StringBuilder();
            //拼接保存路径
            sb.append(basePath).append(fileName);
            visitUrl = visitUrl.concat(fileName);
            File f = new File(sb.toString());
            if(!f.exists()){
                f.getParentFile().mkdirs();
            }
            OutputStream out = new FileOutputStream(f);
            FileCopyUtils.copy(upfile.getInputStream(), out);
            params.put("state", "SUCCESS");
            params.put("url", visitUrl);
            params.put("size", upfile.getSize());
            params.put("original", fileName);
            params.put("type", upfile.getContentType());
        } catch (Exception e){
            params.put("state", "ERROR");
        }
        return params;
    }


    @RequestMapping(value="/config")
    public void config(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        try {
            String exec = new ActionEnter(request, rootPath).exec();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }
}

(6)linux及windows资源映射。

package com.foodo.cloud.admin.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;

/**
 * WebMvc配置
 *
 * @author Mark [email protected]
 * @since 3.0.0 2018-01-25
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
        //window下映射,tomcat直接用路径访问
        //registry.addResourceHandler("/**").addResourceLocations("file:"+"D:/");
        //linux下映射,tomcat直接用路径访问,表示映射fooUpload下面所有文件
        registry.addResourceHandler("/**").addResourceLocations("file:"+"/fooUpload/");
        //registry.addResourceHandler("/**").addResourceLocations("file:"+"/");
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();

        //生成json时,将所有Long转换成String
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);

        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(0, jackson2HttpMessageConverter);
    }
}

以上就是后台需要配置的代码,现在看前端。

(1)下载1.4.3.3 Jsp 版本代码:在resources文件下新建statics/ueditor文件,把ueditor1_4_3_3-utf8-jsp\utf8-jsp下面所有文件都放在ueditor中。lib下面所有包在maven中引用,除啦ueditor.jar外,因为我们后台已有源码,故不用引用它。

(2)config.json配置文件改成心下。

/* 前后端通信相关的配置,注释只允许使用多行方式 */
{
    /* 上传图片配置项 */
    /*"basePath": "D:/",*/ /* windows */
    "basePath": "/fooUpload", /* linux */
    "imageActionName": "uploadimage", /* 执行上传图片的action名称 */
    "imageFieldName": "upfile", /* 提交的图片表单名称 */
    "imageMaxSize": 2048000, /* 上传大小限制,单位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
    "imageCompressEnable": true, /* 是否压缩图片,默认是true */
    "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
    "imageInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageUrlPrefix": "http://192.168.254.37:8080", /* 图片访问路径前缀 */
    "imagePathFormat": "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
                                /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
                                /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
                                /* {time} 会替换成时间戳 */
                                /* {yyyy} 会替换成四位年份 */
                                /* {yy} 会替换成两位年份 */
                                /* {mm} 会替换成两位月份 */
                                /* {dd} 会替换成两位日期 */
                                /* {hh} 会替换成两位小时 */
                                /* {ii} 会替换成两位分钟 */
                                /* {ss} 会替换成两位秒 */
                                /* 非法字符 \ : * ? " < > | */
                                /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */

    /* 涂鸦图片上传配置项 */
    "scrawlActionName": "uploadscrawl", /* 执行上传涂鸦的action名称 */
    "scrawlFieldName": "upfile", /* 提交的图片表单名称 */
    "scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "scrawlMaxSize": 2048000, /* 上传大小限制,单位B */
    "scrawlUrlPrefix": "", /* 图片访问路径前缀 */
    "scrawlInsertAlign": "none",

    /* 截图工具上传 */
    "snapscreenActionName": "uploadimage", /* 执行上传截图的action名称 */
    "snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "snapscreenUrlPrefix": "", /* 图片访问路径前缀 */
    "snapscreenInsertAlign": "none", /* 插入的图片浮动方式 */

    /* 抓取远程图片配置 */
    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage", /* 执行抓取远程图片的action名称 */
    "catcherFieldName": "source", /* 提交的图片列表表单名称 */
    "catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "catcherUrlPrefix": "", /* 图片访问路径前缀 */
    "catcherMaxSize": 2048000, /* 上传大小限制,单位B */
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取图片格式显示 */

    /* 上传视频配置 */
    "videoActionName": "uploadvideo", /* 执行上传视频的action名称 */
    "videoFieldName": "upfile", /* 提交的视频表单名称 */
    "videoPathFormat": "/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "videoUrlPrefix": "http://192.168.254.37:8080", /* 视频访问路径前缀 */
    "videoMaxSize": 102400000, /* 上传大小限制,单位B,默认100MB */
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */

    /* 上传文件配置 */
    "fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */
    "fileFieldName": "upfile", /* 提交的文件表单名称 */
    "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "fileUrlPrefix": "", /* 文件访问路径前缀 */
    "fileMaxSize": 51200000, /* 上传大小限制,单位B,默认50MB */
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ], /* 上传文件格式显示 */

    /* 列出指定目录下的图片 */
    "imageManagerActionName": "listimage", /* 执行图片管理的action名称 */
    "imageManagerListPath": "/ueditor/jsp/upload/image/", /* 指定要列出图片的目录 */
    "imageManagerListSize": 20, /* 每次列出文件数量 */
    "imageManagerUrlPrefix": "", /* 图片访问路径前缀 */
    "imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */

    /* 列出指定目录下的文件 */
    "fileManagerActionName": "listfile", /* 执行文件管理的action名称 */
    "fileManagerListPath": "/ueditor/jsp/upload/file/", /* 指定要列出文件的目录 */
    "fileManagerUrlPrefix": "", /* 文件访问路径前缀 */
    "fileManagerListSize": 20, /* 每次列出文件数量 */
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ] /* 列出的文件类型 */

}

对config.json进行以下说明。

1)新加basePath路径,以后上传的文件都在这下面。

2)"imageActionName": "uploadimage", /* 执行上传图片的action名称 */,"videoActionName": "uploadvideo", /* 执行上传视频的action名称 */,等action,名字不要做任何修改。我们自己写的config类,是根据action名称不同做相应的转换。

3)imageUrlPrefix:图片访问路径前缀需要改你访问项目的路径。

4)imagePathFormat:/upload/image/......保存路径是,basePath+imagePathFormat=/fooUpload/upload/image/.....,图片访问路径就是前缀+保存路径。

5)找到ueditor.config.js,里面有serverUrl 改成以下。

  var RealUrl =  "http://192.168.254.37:8080";//真实的RealUrl是项目访问的路径
   /**
    * 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。
    */
   window.UEDITOR_CONFIG = {

       //为编辑器实例添加一个路径,这个不能被注释
       UEDITOR_HOME_URL: URL

       // 服务器统一请求接口路径,/web/fileUpload/config就是前面自己写的类:FileUploadController 
       , serverUrl: RealUrl + "/web/fileUpload/config"

      }

到此为止ueditor完全配置好,可以愉快的访问啦。

2、ueditor 解决视频回显 src链接丢失问题

解决:ueditor.config.js 365 行,whiteList  拼错了 whitList---》whiteList

参考url:

1、https://blog.csdn.net/qq_33745799/article/details/70031641

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章