ueditor使用_3_图片视频等上传

1. 在初始化加载时候,调用serverUrl地址,传递参数获取

ueditor\jsp\config.json的配置信息

如果.json路径有问题,就会在初始化时前端js报错。所以除了一部分用ueditor的java代码,一部分修改了。所以重写了ueditor的部分代码

2. 后面的图片和视频上传,也是调用serverUrl地址

我用的是springmvc的框架


1. 入口  xxController.java

    @RequestMapping(value = "uEditActionEnter")
    @ResponseBody
    public void uEditActionEnter(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error("setCharacterEncoding:",e);
        }
        response.setHeader("Content-Type" , "text/html");
        String roolPath = request.getSession().getServletContext().getRealPath("/");
        String configStr = new MyActionEnter(request, ueditorConfigPath,saveLocalAbsoutePath).exec();


        try {
            response.getWriter().write(configStr);
        } catch (IOException e) {
            log.error("return write:", e);
        }
    }

ueditorConfigPath:config. json文件的绝对路径

saveLocalAbsoutePath:保存图片或者视频的全路径

MyActionEnter:是重写了ActionEnter类


2.MyActionEnter.java

import com.baidu.ueditor.define.ActionMap;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;
import com.baidu.ueditor.hunter.FileManager;
import com.baidu.ueditor.hunter.ImageHunter;
import com.zte.alm.safety.infrastructure.ueditor.upload.MyUploader;


import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * Created by 00194550 on 2016/8/4.
 */
public class MyActionEnter {
    private HttpServletRequest request = null;
    private String rootPath = null;
    private String configPath = null;
    private String contextPath = null;
    private String actionType = null;
    private MyConfigManager configManager = null;


    public MyActionEnter(HttpServletRequest request, String configPath) {
        this.request = request;
        this.configPath = configPath;
        this.actionType = request.getParameter("action");
        this.contextPath = request.getContextPath();
        this.configManager = MyConfigManager.getInstance(this.configPath, this.contextPath, request.getRequestURI());


    }


    public MyActionEnter(HttpServletRequest request, String configPath,String rootPath) {
        this.request = request;
        this.rootPath = rootPath;
        this.configPath = configPath;
        this.actionType = request.getParameter("action");
        this.contextPath = request.getContextPath();
        this.configManager = MyConfigManager.getInstance(this.configPath, this.contextPath, rootPath);


    }
    public String exec() {
        String callbackName = this.request.getParameter("callback");
        return callbackName != null?(!this.validCallbackName(callbackName)?(new BaseState(false, 401)).toJSONString():callbackName + "(" + this.invoke() + ");"):this.invoke();
    }


    public String invoke() {
        if(this.actionType != null && ActionMap.mapping.containsKey(this.actionType)) {
            if(this.configManager != null && this.configManager.valid()) {
                State state = null;
                int actionCode = ActionMap.getType(this.actionType);
                Map conf = null;
                switch(actionCode) {
                    case 0:
                        return this.configManager.getAllConfig().toString();
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        conf = this.configManager.getConfig(actionCode);
                        state = (new MyUploader(this.request, conf)).doExec();
                        break;
                    case 5:
                        conf = this.configManager.getConfig(actionCode);
                        String[] list = this.request.getParameterValues((String)conf.get("fieldName"));
                        state = (new ImageHunter(conf)).capture(list);
                        break;
                    case 6:
                    case 7:
                        conf = this.configManager.getConfig(actionCode);
                        int start = this.getStartIndex();
                        state = (new FileManager(conf)).listFile(start);
                }


                return state.toJSONString();
            } else {
                return (new BaseState(false, 102)).toJSONString();
            }
        } else {
            return (new BaseState(false, 101)).toJSONString();
        }
    }


    public int getStartIndex() {
        String start = this.request.getParameter("start");


        try {
            return Integer.parseInt(start);
        } catch (Exception var3) {
            return 0;
        }
    }


    public boolean validCallbackName(String name) {
        return name.matches("^[a-zA-Z_]+[\\w0-9_]*$");
    }
}


3. 重写:MyConfigManager.java

import org.json.JSONArray;
import org.json.JSONObject;


import java.io.*;
import java.util.HashMap;
import java.util.Map;


public final class MyConfigManager {
    private final String rootPath;
    private final String configPath;
    private final String originalPath;
    private final String contextPath;
    private static final String configFileName = "config.json";
    private String parentPath = null;
    private JSONObject jsonConfig = null;
    private static final String SCRAWL_FILE_NAME = "scrawl";
    private static final String REMOTE_FILE_NAME = "remote";


    private MyConfigManager(String configPath, String contextPath, String rootPath) throws FileNotFoundException, IOException {
        this.configPath = configPath.replace("\\", "/");
        this.contextPath = contextPath;
        this.rootPath = rootPath;
        this.originalPath = this.configPath;
        this.initEnv();
    }


    public static MyConfigManager getInstance(String configPath, String contextPath, String rootPath) {
        try {
            return new MyConfigManager(configPath, contextPath, rootPath);
        } catch (Exception var4) {
            return null;
        }
    }


    public boolean valid() {
        return this.jsonConfig != null;
    }


    public JSONObject getAllConfig() {
        return this.jsonConfig;
    }


    public Map<String, Object> getConfig(int type) {
        HashMap conf = new HashMap();
        String savePath = null;
        switch(type) {
            case 1:
                conf.put("isBase64", "false");
                conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("imageMaxSize")));
                conf.put("allowFiles", this.getArray("imageAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("imageFieldName"));
                savePath = this.jsonConfig.getString("imagePathFormat");
                break;
            case 2:
                conf.put("filename", "scrawl");
                conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("scrawlMaxSize")));
                conf.put("fieldName", this.jsonConfig.getString("scrawlFieldName"));
                conf.put("isBase64", "true");
                savePath = this.jsonConfig.getString("scrawlPathFormat");
                break;
            case 3:
                conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("videoMaxSize")));
                conf.put("allowFiles", this.getArray("videoAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("videoFieldName"));
                savePath = this.jsonConfig.getString("videoPathFormat");
                break;
            case 4:
                conf.put("isBase64", "false");
                conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("fileMaxSize")));
                conf.put("allowFiles", this.getArray("fileAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("fileFieldName"));
                savePath = this.jsonConfig.getString("filePathFormat");
                break;
            case 5:
                conf.put("filename", "remote");
                conf.put("filter", this.getArray("catcherLocalDomain"));
                conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("catcherMaxSize")));
                conf.put("allowFiles", this.getArray("catcherAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("catcherFieldName") + "[]");
                savePath = this.jsonConfig.getString("catcherPathFormat");
                break;
            case 6:
                conf.put("allowFiles", this.getArray("fileManagerAllowFiles"));
                conf.put("dir", this.jsonConfig.getString("fileManagerListPath"));
                conf.put("count", Integer.valueOf(this.jsonConfig.getInt("fileManagerListSize")));
                break;
            case 7:
                conf.put("allowFiles", this.getArray("imageManagerAllowFiles"));
                conf.put("dir", this.jsonConfig.getString("imageManagerListPath"));
                conf.put("count", Integer.valueOf(this.jsonConfig.getInt("imageManagerListSize")));
        }


        conf.put("savePath", savePath);
        conf.put("rootPath", this.rootPath);
        return conf;
    }


    private void initEnv() throws FileNotFoundException, IOException {
        File file = new File(this.originalPath);
        if(!file.isAbsolute()) {
            file = new File(file.getAbsolutePath());
        }


        this.parentPath = this.originalPath;
        String configContent = this.readFile(this.getConfigPath());


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


    }


    private String getConfigPath() {
        return this.parentPath + File.separator + "config.json";
    }


    private String[] getArray(String key) {
        JSONArray jsonArray = this.jsonConfig.getJSONArray(key);
        String[] result = new String[jsonArray.length()];
        int i = 0;


        for(int len = jsonArray.length(); i < len; ++i) {
            result[i] = jsonArray.getString(i);
        }


        return result;
    }


    private String readFile(String path) throws IOException {
        StringBuilder builder = new StringBuilder();


        try {
            InputStreamReader reader = new InputStreamReader(new FileInputStream(path), "UTF-8");
            BufferedReader bfReader = new BufferedReader(reader);
            String tmpContent = null;


            while((tmpContent = bfReader.readLine()) != null) {
                builder.append(tmpContent);
            }


            bfReader.close();
        } catch (UnsupportedEncodingException var6) {
            ;
        }


        return this.filter(builder.toString());
    }


    private String filter(String input) {
        return input.replaceAll("/\\*[\\s\\S]*?\\*/", "");
    }
}

4.重写 MyUploader和MyBinaryUploader两个类



import com.baidu.ueditor.define.State;
import com.baidu.ueditor.upload.Base64Uploader;


import javax.servlet.http.HttpServletRequest;
import java.util.Map;


public class MyUploader {
    private HttpServletRequest request = null;
    private Map<String, Object> conf = null;


    public MyUploader(HttpServletRequest request, Map<String, Object> conf) {
        this.request = request;
        this.conf = conf;
    }


    public final State doExec() {
        String filedName = (String)this.conf.get("fieldName");
        State state = null;
        if("true".equals(this.conf.get("isBase64"))) {
            state = Base64Uploader.save(this.request.getParameter(filedName), this.conf);
        } else {
            state = MyBinaryUploader.save(this.request, this.conf);
        }


        return state;
    }
}






import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import com.baidu.ueditor.upload.StorageManager;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


public class MyBinaryUploader {
    public MyBinaryUploader() {
    }


    public static final State save(HttpServletRequest request, Map<String, Object> conf) {


        boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;
        if(!ServletFileUpload.isMultipartContent(request)) {
            return new BaseState(false, 5);
        } else {
            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
            if(isAjaxUpload) {
                upload.setHeaderEncoding("UTF-8");
            }


            try {
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                List<MultipartFile> fileList = multipartRequest.getFiles(conf.get("fieldName").toString());
                if(fileList == null || fileList.size() == 0){
                    return new BaseState(false, 7);
                }else{
                    for(int i=0;i<fileList.size();i++){
                        MultipartFile multipartFile = fileList.get(0);
                        String savePath = (String)conf.get("savePath");
                        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, 8);
                        } else {
                            savePath = PathFormat.parse(savePath, originFileName);
                            String physicalPath = (String)conf.get("rootPath") + savePath;
                            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;
                        }
                    }


                    return null;
                }
            }  catch (IOException var15) {
                return new BaseState(false, 4);
            }catch (Exception var16) {
                return new BaseState(false, 6);
            }
        }
    }


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


配置config.json 修改,主要修改:访问地址,存放的相对地址

"imageUrlPrefix": "http://localhost:9090/", /* 图片访问路径前缀 */
"imagePathFormat": "/ueditor/image/{yyyy}{mm}{dd}/{time}{rand:6}_{filename}",

其他对应的修改即可


在上传视频的时候,出现img中_src没有了,主要是白名单的问题,和居中报错问题解决
修改:

ueditor.config.js中

img:    ['src', 'alt', 'title', 'width', 'height', 'id', '_src', 'loadingclass', 'class','style','_url'],

p:      ['class', 'style','id'],


请修改ueditor.config.js  里面的白名单设置。由于白名单里面过滤掉了各种标签的属性,到时样式跟id之类的被清空了。

img:    ['src', 'alt', 'title', 'width', 'height', 'id', '_src', 'loadingclass','style', 'class', '_url'],  

当重新编辑上传的视频的时候,ueditor自动将video转换为img标签(详细怎么转换请看video.js中的switchImgAndVideo)由于img标签的白名单不存在 class  style 以及_url所以当ueditor将其转为html代码的时候这部分属性被清空,到时编辑的时候显示的是图片而不是视频。img 跟video的居中报错问题也是因为白名单里面没  id跟style  导致根据id去取的时候取不到对象。将p标签的白名单加上id跟style即可解决问题。









  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值