ueditor将图片上传至服务器地址的方法

说明:ueditor控件默认是把图片上传到默认的控件内部地址的,如果我们重新换包,图片肯定会清空。我们在开发的时候,肯定要将这个目录上传到固定的目录(文件服务器)中,防止被清空。

准备:1.我的工程(工程名为test)的服务器容器是本地的tomcat,本地目录:E:\apache-tomcat-7.4.44\webapps\test,端口为2022。

2.文件服务器是同一个tomcat下与工程名平级的目录里:E:\apache-tomcat-7.4.44\webapps\newsImg。也就是说直接访问(不用带工程名)这里面的图片可以的。

比如在该目录下新建abc.txt,重启tomcat,浏览器直接访问:http://localhost:2022/newsImg/abc.txt是可以直接访问的。

3.准备好了之后,下载ueditor控件(我的是jsp版本,后台是java的spring框架)地址:http://ueditor.baidu.com/website/download.html#ueditor

下载之后,直接放入工程的静态文件目录下,另外在jsp/lib目录下有jar包,需要移到工程的lib目录下

如图:


4.若改成文件存储的外部地址,则需要修改源码,其实就是改lib下面的ueditor-1.1.6.jar。源码的话,需要在网上找一下,我这边提供一下(下文给下载链接),即ueditor-jsp工程目录如下:在upload目录下添加UeditorActionEnter类:


在UeditorActionEnter的invoke方法中设置rootpath,即上传地址目录:


UeditorActionEnter类代码如下:

package com.baidu.ueditor.upload;

import com.baidu.ueditor.ActionEnter;
import com.baidu.ueditor.ConfigManager;
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.baidu.ueditor.upload.Uploader;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
 * 2018-02-24
 * @author wyf
 *
 */
public class UeditorActionEnter extends ActionEnter {
    private HttpServletRequest request = null;
    private String rootPath = null;
    private String contextPath = null;
    private String actionType = null;
    private ConfigManager configManager = null;
    public UeditorActionEnter(HttpServletRequest request, String rootPath) {
        super(request, rootPath);
        this.request = request;
        this.rootPath = rootPath;
        this.actionType = request.getParameter("action");
        this.contextPath = request.getContextPath();
        this.configManager = ConfigManager.getInstance(this.rootPath, this.contextPath, request.getRequestURI());
    }    
@Override    
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<String, Object> conf = null;
                switch (actionCode) { 
                   case 0: 
                       return this.configManager.getAllConfig().toString();
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        conf = this.configManager.getConfig(actionCode);
                        //注意再这里修改rootPath和savePath,上传的实际路径为rootPath+savePath
                        conf.put("rootPath", "E:/apache-tomcat-7.4.44/webapps/");
                        conf.put("savePath", conf.get("savePath"));
                        state = (new Uploader(this.request, conf)).doExec();
                        break;
                    case 5:
                        conf = this.configManager.getConfig(actionCode);
                        //注意再这里修改rootPath和savePath,上传的实际路径为rootPath+savePath
                        conf.put("rootPath", "E:/apache-tomcat-7.4.44/webapps/");
                        conf.put("savePath", conf.get("savePath"));
                        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);
                       //注意再这里修改rootPath和savePath,上传的实际路径为rootPath+savePath
                        conf.put("rootPath", "E:/apache-tomcat-7.4.44/webapps/");
                        conf.put("savePath", conf.get("savePath"));
                        conf.put("dir", "/upload" + conf.get("dir"));
                        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();
        }
    }
}

在BinaryUploader类获取配置文件里配置的physicalPath变量:(这个physicalPath变量在后面配置文件中会讲)



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.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class BinaryUploader {

	public static void main(String[] args) {
		System.out.println(null + "");
	}
	public static final State save(HttpServletRequest request,
			Map<String, Object> conf) {
		FileItemStream fileStream = null;
		boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;

		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}

		ServletFileUpload upload = new ServletFileUpload(
				new DiskFileItemFactory());

        if ( isAjaxUpload ) {
            upload.setHeaderEncoding( "UTF-8" );
        }

		try {
			FileItemIterator iterator = upload.getItemIterator(request);

			while (iterator.hasNext()) {
				fileStream = iterator.next();

				if (!fileStream.isFormField())
					break;
				fileStream = null;
			}

			if (fileStream == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}

			String savePath = (String) conf.get("savePath");//  /ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}
			String originFileName = fileStream.getName();//111.png
			String suffix = FileType.getSuffixByFilename(originFileName);//.png

			originFileName = originFileName.substring(0,
					originFileName.length() - suffix.length());//111
			savePath = savePath + suffix;///ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}.png

			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);///ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}.png

//			String physicalPath = (String) conf.get("rootPath") + savePath;//D:/Program Files/apache-tomcat-7.0.64/wtpwebapps//ueditor/jsp/upload/image/20151116/1447675575987060166.png
			/*************zrk修改:改变文件存储路径*************/
			String physicalPath = (String) conf.get("physicsPath");
			if(physicalPath!=null&&!"".equals(physicalPath))
				physicalPath += savePath;
			else
				physicalPath = conf.get("rootPath") + savePath;
			/**************************/
			InputStream is = fileStream.openStream();
			State storageState = StorageManager.saveFileByInputStream(is,
					physicalPath, maxSize);
			is.close();

			if (storageState.isSuccess()) {
				if(storageState.getInfoString("url")==null){
					storageState.putInfo("url", PathFormat.format(savePath));
				}
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}

			return storageState;
		} catch (FileUploadException e) {
			return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		} 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);
	}
}



改完之后,需要把这个工程右键打成jar包,放到我们test工程lib下,至此修改源码完成。我们的准备工作完成,然后开始写页面和配置ueditor控件参数。

开始设置:1.在我们的要显示是的jsp页面上面(uedit.jsp)导入js和初始化ueditor控件

代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>        
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>        
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">        
<html>        
    <head>        
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        
        <title>123</title> 
        <script type="text/javascript" charset="utf-8" src="http://localhost:2022/test/static/utf8-jsp/ueditor.config.js"></script>
    	<script type="text/javascript" charset="utf-8" src="http://localhost:2022/test/static/utf8-jsp/ueditor.all.min.js"> </script>
    	<script type="text/javascript" charset="utf-8" src="http://localhost:2022/test/static/utf8-jsp/lang/zh-cn/zh-cn.js"></script>

	    <style type="text/css">
	        div{
	            width:100%;
	        }
	    </style>       
    </head>        
            
    <body>        
    <div>
	    <textarea name="content" id="content" style='width:80%;height:100%;'></textarea>
	</div>

    <script type="text/javascript">
     
     //初始化富文本 
      var ue = UE.getEditor('content',{
                    toolbars: [
                        [
                            'undo', //撤销
                            'bold', //加粗
                            'italic', //斜体
                            'underline', //下划线
                            'strikethrough', //删除线
                            'formatmatch', //格式刷
                            'selectall', //全选
                            'link', //超链接
                            'unlink', //取消链接
                            'fontfamily', //字体
                            'fontsize', //字号
                            'insertimage', //多图上传
                            'help', //帮助
                            'justifyleft', //居左对齐
                            'justifyright', //居右对齐
                            'justifycenter', //居中对齐
                            'justifyjustify', //两端对齐
                            'forecolor', //字体颜色
                            'backcolor', //背景色
                            'touppercase', //字母大写
                            'tolowercase', //字母小写
                        ]
                    ],
                    initialFrameWidth:700,//宽度
                    initialFrameHeight :320,//高度
                });
    </script>
    </body> 
</html>    

这时我们访问这个路径:http://localhost:2022/test/uedit/toView.do,可以预览到页面:


2.设置ueditor控件的config.json配置文件(部分代码):


physicsPath:是这里配置的路径前缀,其实相当于文件服务器的路径,我之前改过UeditorActionEnter类的rootPath,其实这里不需要设置的。

imageUrlPrefix:请求前缀 (这里建议为空,因为浏览器会自带前缀ip和端口的

imagePathFormat:文件服务器下的子路径,就是说完整的路径是physicsPath+imagePathFormat

代码如下:

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

3.设置controller.jsp代码,改成我们自己加的那个类的方法。


代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	import="com.baidu.ueditor.upload.UeditorActionEnter"
    pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%

    request.setCharacterEncoding( "utf-8" );
	response.setHeader("Content-Type" , "text/html");
	
	String rootPath = application.getRealPath( "/" );
	
	out.write( new UeditorActionEnter( request, rootPath).exec() );
	
%>


到此配置完成,现在可以测试了,是可以成功传入我们设置的文件服务器中



直接获取图片地址:http://localhost:2022/newsImg/1519962839068090692.png


大功告成。

下面附源码

http://download.csdn.net/download/yufeng005/10266299

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值