您的位置:首页 > 产品设计 > UI/UE

Ueditor使用教程(高级进阶)

2016-12-26 21:21 302 查看
上一篇讲了Ueditor的基本使用教程,如果现在想做文件上传之类的,则需要在配置文件设置上传路径。

1:在前台设置ueditor的HOME路径

<script type="text/javascript" charset="utf-8">window.UEDITOR_HOME_URL = "<%=path%>/plugins/ueditor/";</script>

2:配置文件上传路径



3:这边是上传到jsp页面,需要在jsp页面进行数据的处理

一下是代码

   <%@ page language="java" contentType="text/html; charset=utf-8"

             pageEncoding="utf-8"%>

        <%@ page import="java.util.Properties" %>

        <%@ page import="java.util.List" %>

        <%@ page import="java.util.Iterator" %>

        <%@ page import="java.util.Arrays" %>

        <%@ page import="java.io.FileInputStream" %>

        <%@ page import="ueditor.Uploader" %> ---->这个是java数据处理类,注意,是自己引入的,包名和类名,不要以为是官方提供的

        <%@ page import="java.io.File" %>

        <%@ page import="java.util.Map" %>

        <%@ page import="com.fh.util.*" %>

            <%

request.setCharacterEncoding( Uploader.ENCODEING ); 

response.setCharacterEncoding( Uploader.ENCODEING );

String currentPath = request.getRequestURI().replace( request.getContextPath(), "" );

File currentFile = new File( currentPath );

currentPath = currentFile.getParent() + File.separator;

System.out.println("=================="+currentPath);

//加载配置文件
//String propertiesPath = request.getSession().getServletContext().getRealPath( currentPath + "config.properties" );  下面会提供

String propertiesPath = request.getRealPath("/plugins/ueditor/jsp/config.properties");

Properties properties = new Properties();

try {

    properties.load( new FileInputStream( propertiesPath ) );

} catch ( Exception e ) {

    //加载失败的处理

    e.printStackTrace();

}

List<String> savePath = Arrays.asList( properties.getProperty( "savePath" ).split( "," ) );

//获取存储目录结构

if ( request.getParameter( "fetch" ) != null ) {

    response.setHeader( "Content-Type", "text/javascript" );

    //构造json数据

    Iterator<String> iterator = savePath.iterator();

    String dirs = "[";

    while ( iterator.hasNext() ) {

        dirs += "'" + iterator.next() +"'";

        if ( iterator.hasNext() ) {

            dirs += ",";

        }

    }

    dirs += "]";

    response.getWriter().print( "updateSavePath( "+ dirs +" );" );

    return;

}

Uploader up = new Uploader(request);

// 获取前端提交的path路径

String dir = request.getParameter( "dir" );

//普通请求中拿不到参数, 则从上传表单中拿

if ( dir == null ) {

    dir = up.getParameter("dir");

}

if ( dir == null || "".equals( dir ) ) {

    //赋予默认值

    dir = savePath.get( 0 );

    //安全验证

} else if ( !savePath.contains( dir ) ) {

    response.getWriter().print( "{'state':'\\u975e\\u6cd5\\u4e0a\\u4f20\\u76ee\\u5f55'}" );

    return;

}
//上面不懂不话先放着,下面是调用ueditor.Uploader执行的代码

up.setSavePath( dir );  

String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};

up.setAllowFiles(fileType);

up.setMaxSize(500 * 1024); //单位KB

up.upload();

//这个是将上传信息返回给前台。客户端会根据返回的url进行

response.getWriter().print("{'original':'"+up.getOriginalName()+"','url':'"+up.getUrl()+"','title':'"+up.getTitle()+"','state':'"+up.getState()+"'}");

%>

4:ueditor.Uploader类

这个类以及对应的包名是自己写的,这个要注意,可以直接复制,再进行修改

package ueditor;

import java.io.*;

import java.text.SimpleDateFormat;

import java.util.*;

import org.apache.commons.io.IOUtils;

import org.apache.commons.fileupload.*;

import org.apache.commons.fileupload.servlet.*;

import org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException;

import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import com.fh.service.qiniuyun.QiniuyunService;

import sun.misc.BASE64Decoder;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;

/**

 * UEditor

 *

 *
ce88
/

public class Uploader {

    

//    @Resource(name="qiniuyunService")

//    private QiniuyunService qiniuyunService;

    // 文件大小常量, 单位kb

    private static final int MAX_SIZE = 500 * 1024;

    // 输出文件地址

    private String url = "";

    // 上传文件名

    private String fileName = "";

    // 状态

    private String state = "";

    // 文件类型

    private String type = "";

    // 原始文件名

    private String originalName = "";

    // 文件大小

    private String size = "";

    private HttpServletRequest request = null;

    private String title = "";

    // 保存路径

    private String savePath = "upload";

    // 文件允许格式

    private String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",

            ".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };

    // 文件大小限制,单位Byte

    private long maxSize = 0;

    private HashMap<String, String> errorInfo = new HashMap<String, String>();

    private Map<String, String> params = null;

    // 上传的文件数据

    private InputStream inputStream = null;

    public static final String ENCODEING = System.getProperties().getProperty(

            "file.encoding");

    public Uploader(HttpServletRequest request) {

        this.request = request;

        this.params = new HashMap<String, String>();

        this.setMaxSize(Uploader.MAX_SIZE);

        HashMap<String, String> tmp = this.errorInfo;

        tmp.put("SUCCESS", "SUCCESS"); // 默认成功

        // 未包含文件上传域

        tmp.put("NOFILE",

                "\\u672a\\u5305\\u542b\\u6587\\u4ef6\\u4e0a\\u4f20\\u57df");

        // 不允许的文件格式

        tmp.put("TYPE",

                "\\u4e0d\\u5141\\u8bb8\\u7684\\u6587\\u4ef6\\u683c\\u5f0f");

        // 文件大小超出限制

        tmp.put("SIZE",

                "\\u6587\\u4ef6\\u5927\\u5c0f\\u8d85\\u51fa\\u9650\\u5236");

        // 请求类型错误

        tmp.put("ENTYPE", "\\u8bf7\\u6c42\\u7c7b\\u578b\\u9519\\u8bef");

        // 上传请求异常

        tmp.put("REQUEST", "\\u4e0a\\u4f20\\u8bf7\\u6c42\\u5f02\\u5e38");

        // 未找到上传文件

        tmp.put("FILE", "\\u672a\\u627e\\u5230\\u4e0a\\u4f20\\u6587\\u4ef6");

        // IO异常

        tmp.put("IO", "IO\\u5f02\\u5e38");

        // 目录创建失败

        tmp.put("DIR", "\\u76ee\\u5f55\\u521b\\u5efa\\u5931\\u8d25");

        // 未知错误

        tmp.put("UNKNOWN", "\\u672a\\u77e5\\u9519\\u8bef");

        this.parseParams();

    }

    public void upload() throws Exception {

        boolean isMultipart = ServletFileUpload

                .isMultipartContent(this.request);

        if (!isMultipart) {

            this.state = this.errorInfo.get("NOFILE");

            return;

        }

        if (this.inputStream == null) {

            this.state = this.errorInfo.get("FILE");

            return;

        }

        // 存储title

        this.title = this.getParameter("pictitle");

        try {

            String savePath = this.getFolder(this.savePath);

            if (!this.checkFileType(this.originalName)) {

                this.state = this.errorInfo.get("TYPE");

                return;

            }

            this.fileName = "ww/"+this.getName(this.originalName);

            this.type = this.getFileExt(this.fileName);

        //    this.url = savePath + "/" + this.fileName;

          //以下是执行代码,本人用的是将数据上传到七牛云服务器

            

            System.out.println("正在上传。。。");

            System.out.println("this.inputStream="+this.inputStream.available());

            System.out.println("this.fileName="+this.fileName);

            QiniuyunService qiniuyunService =new QiniuyunService();

            qiniuyunService.upload2(this.inputStream, this.fileName);

            System.out.println("上传成功。。。获取上传路径");

            this.url=qiniuyunService.download(this.fileName+"?imageView2/1/w/150/h/150");

            System.out.println("url="+this.url);

           

// 这个是本地上传,这边也提供

//         FileOutputStream fos = new FileOutputStream(

//                    this.getPhysicalPath(this.url));//存储路径

//            BufferedInputStream bis = new BufferedInputStream(this.inputStream);

//            byte[] buff = new byte[128];

//            int count = -1;

//

//            while ((count = bis.read(buff)) != -1) {

//

//                fos.write(buff, 0, count);

//

//            }

//

//            bis.close();

//            fos.close();

            this.state = this.errorInfo.get("SUCCESS");

        } catch (Exception e) {

            e.printStackTrace();

            this.state = this.errorInfo.get("IO");

        }

    }

    /**

     * 接受并保存以base64格式上传的文件

     *

     * @param fieldName

     */

    public void uploadBase64(String fieldName) {

        String savePath = this.getFolder(this.savePath);

        String base64Data = this.request.getParameter(fieldName);

        this.fileName = this.getName("test.png");

        this.url = savePath + "/" + this.fileName;

        BASE64Decoder decoder = new BASE64Decoder();

        try {

            File outFile = new File(this.getPhysicalPath(this.url));

            OutputStream ro = new FileOutputStream(outFile);

            byte[] b = decoder.decodeBuffer(base64Data);

            for (int i = 0; i < b.length; ++i) {

                if (b[i] < 0) {

                    b[i] += 256;

                }

            }

            ro.write(b);

            ro.flush();

            ro.close();

            this.state = this.errorInfo.get("SUCCESS");

        } catch (Exception e) {

            this.state = this.errorInfo.get("IO");

        }

    }

    public String getParameter(String name) {

        return this.params.get(name);

    }

    /**

     * 文件类型判断

     *

     * @param fileName

     * @return

     */

    private boolean checkFileType(String fileName) {

        Iterator<String> type = Arrays.asList(this.allowFiles).iterator();

        while (type.hasNext()) {

            String ext = type.next();

            if (fileName.toLowerCase().endsWith(ext)) {

                return true;

            }

        }

        return false;

    }

    /**

     * 获取文件扩展名

     *

     * @return string

     */

    private String getFileExt(String fileName) {

        return fileName.substring(fileName.lastIndexOf("."));

    }

    private void parseParams() {

        DiskFileItemFactory dff = new DiskFileItemFactory();

        try {

            ServletFileUpload sfu = new ServletFileUpload(dff);

            sfu.setSizeMax(this.maxSize);

            sfu.setHeaderEncoding(Uploader.ENCODEING);

            FileItemIterator fii = sfu.getItemIterator(this.request);

            while (fii.hasNext()) {

                FileItemStream item = fii.next();

                // 普通参数存储

                if (item.isFormField()) {

                    this.params.put(item.getFieldName(),

                            this.getParameterValue(item.openStream()));

                } else {

                    // 只保留一个

                    if (this.inputStream == null) {

                        this.inputStream = item.openStream();

                        this.originalName = item.getName();

                        return;

                    }

                }

            }

        } catch (Exception e) {

            this.state = this.errorInfo.get("UNKNOWN");

        }

    }

    /**

     * 依据原始文件名生成新文件名

     *

     * @return

     */

    private String getName(String fileName) {

        Random random = new Random();

        return this.fileName = "" + random.nextInt(10000)

                + System.currentTimeMillis() + this.getFileExt(fileName);

    }

    /**

     * 根据字符串创建本地目录 并按照日期建立子目录返回

     *

     * @param path

     * @return

     */

    private String getFolder(String path) {

        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");

        path += "/" + formater.format(new Date());

        File dir = new File(this.getPhysicalPath(path));

        if (!dir.exists()) {

            try {

                dir.mkdirs();

            } catch (Exception e) {

                this.state = this.errorInfo.get("DIR");

                return "";

            }

        }

        return path;

    }

    /**

     * 根据传入的虚拟路径获取物理路径

     *

     * @param path

     * @return

     */

    private String getPhysicalPath(String path) {

        String servletPath = this.request.getServletPath();

        String realPath = this.request.getSession().getServletContext()

                .getRealPath(servletPath);

        return new File(realPath).getParent() + "/" + path;

    }

    /**

     * 从输入流中获取字符串数据

     *

     * @param in

     *            给定的输入流, 结果字符串将从该流中读取

     * @return 从流中读取到的字符串

     */

    private String getParameterValue(InputStream in) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String result = "";

        String tmpString = null;

        try {

            while ((tmpString = reader.readLine()) != null) {

                result += tmpString;

            }

        } catch (Exception e) {

            // do nothing

        }

        return result;

    }

    private byte[] getFileOutputStream(InputStream in) {

        try {

            return IOUtils.toByteArray(in);

        } catch (IOException e) {

            return null;

        }

    }

    public void setSavePath(String savePath) {

        this.savePath = savePath;

    }

    public void setAllowFiles(String[] allowFiles) {

        this.allowFiles = allowFiles;

    }

    public void setMaxSize(long size) {

        this.maxSize = size * 1024;

    }

    public String getSize() {

        return this.size;

    }

    public String getUrl() {

        System.out.println("====="+this.url);

        return this.url;

    }

    public String getFileName() {

        return this.fileName;

    }

    public String getState() {

        return this.state;

    }

    public String getTitle() {

        return this.title;

    }

    public String getType() {

        return this.type;

    }

    public String getOriginalName() {

        return this.originalName;

    }

}

5:config.properties

#UEditor Config

# \u4FDD\u5B58\u8DEF\u5F84

savePath=upload1,upload2,upload3

# \u4E0A\u4F20\u6587\u4EF6\u540D\u5B57\u683C\u5F0F

fileNameFormat={time}{rand\:6}

完成以上的步骤就可以实现文件上传了,视频上传也是类似的。

觉得有帮到你的朋友点个赞。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: