UEditor应用 —— 图片上传

本文介绍UEditor图片上传功能的实现。javascript

使用的例子项目架构以下:html

freemaker + spring boot + spring mvc + maven 前端

例子项目已上传码云,码云地址以下:java

http://git.oschina.net/imlichao/ueditor-example-image_uploadgit

 

前端部署

下载UEditor项目包,并部署到项目中

pring boot项目放在静态资源目录下web

在页面加载UEditor

<!DOCTYPE HTML>
<html lang="en" class="no-js">

<head>
    <meta charset="UTF-8">
    <title>ueditor demo</title>
    <!-- spring boot默认静态资源跟目录在static下 -->
    <script type="text/javascript" charset="utf-8" src="/ueditor1_4_3_3/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="/ueditor1_4_3_3/ueditor.all.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="/ueditor1_4_3_3/lang/zh-cn/zh-cn.js"></script>
</head>

<body text-align:center>
    <table style="margin:0 auto;">
        <tr><td><h1>ueditor demo</h1></td></tr>
        <tr><td><script id="editor" type="text/plain" style="width:1024px;height:500px;"></script></td></tr>
    </table>
    <script type="text/javascript">
        var ue = UE.getEditor('editor');
    </script>
</body>

</html>

执行效果

到这里UEditor一些基础的编辑功能已经可以使用了,可是像图片上传这一类功能还须要进行后台配置。spring

 

后端部署

目录结构

配置后台统一请求路径

在ueditor.config.js找到serverUrl参数修改成本身的后台请求接收方法json

// 服务器统一请求接口路径
, serverUrl: "/ueditor/interface"

编写请求接收方法后端

/**
     * ueditor 服务器统一请求接口(GET)
     * @param action config 加载时获取配置文件
     * @return
     */
    @RequestMapping(value = "/ueditor/interface", method = RequestMethod.GET)
    @ResponseBody
    public String ueGetInterface(String action) {
        System.out.println("Successful GET interface call");
        return null;
    }

测试请求路径是否设置成功。api

ue在加载时会调用一次serverUrl,咱们能够在接收方法内打断点或打印日志进行测试。

 

在这里要对统一请求路径作一下说明:

ueditor会将全部的后台请求发送至统一请求路径。

不一样的功能会使用不一样的方式提交,获取配置使用GET提交,上传图片或文件使用POST提交,因此接口要分开两个方法写。

既然全部的后台请求都发送到一个接口,那么怎么区分请求的是什么功能呢?答案就是action参数,action传入“config”时表明获取配置,action传入“uploadimage”时表明上传图片,还有其余的值在这里就不作一一列举了,能够本身去看api文档。

设置上传配置

在服务器统一请求接口中获取配置并转换成json形式返回

/**
     * ueditor 服务器统一请求接口(GET)
     * @param action config 加载时获取配置文件
     * @return
     */
    @RequestMapping(value = "/ueditor/interface", method = RequestMethod.GET)
    @ResponseBody
    public String ueGetInterface(String action) {
        System.out.println("Successful GET interface call");
        //建立文件上传配置文件类并转换为json方式返回
        if(action != null && action.equals("config")){
            try {
                ObjectMapper mapper = new ObjectMapper();
                String config = mapper.writeValueAsString(new UeditorUploadConfig());
                return config;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
package pub.lichao.ueditor.controller;

/**
 * Ueditor 文件上传配置
 */
public class UeditorUploadConfig {
    /**
     * 执行上传图片的action名称
     */
    private String imageActionName="uploadimage";
    /**
     * 提交的图片表单名称
     */
    private String imageFieldName="upfile";
    /**
     * 上传大小限制,单位B
     */
    private Integer imageMaxSize=2048000;
    /**
     * 上传图片格式显示
     */
    private String[] imageAllowFiles=new String[]{".png",".jpg",".jpeg",".gif"};
    /**
     * 是否压缩图片
     */
    private Boolean imageCompressEnable=true;
    /**
     * 图片压缩最长边限制
     */
    private Integer imageCompressBorder=1600;

    /**
     * 插入的图片浮动方式
     */
    private String imageInsertAlign="none";

    /**
     * 图片访问路径前缀
     */
    private String imageUrlPrefix="";


    ... get set 方法 ...
}

 

编写图片上传逻辑

本项目将图片保存到了项目本地路径中,在实际应用中每每会将图片保存在专门的图片服务器中。例如阿里云的OSS

/**
     * ueditor 服务器统一请求接口(POST)
     * @param action uploadimage 图片上传
     * @return
     */
    @RequestMapping(value = "/ueditor/interface", method = RequestMethod.POST)
    @ResponseBody
    public String uePostInterface(String action,MultipartFile upfile, HttpServletRequest request) {
        System.out.println("Successful POST interface call");
        //转换json格式工具
        ObjectMapper mapper = new ObjectMapper();
        //返回值对象
        ImageState imageState = new ImageState();
        try {
            //执行图片上传并返回json格式结果
            if(action != null && action.equals("uploadimage")){
                System.out.println("uploadimage");
                //保存文件(将图片上传到项目中,生产应用中会使用OSS等文件服务器进行存放)
                String dirPath = request.getSession().getServletContext().getRealPath("/images");
                new File(dirPath).mkdirs(); //建立目录
                System.out.println("图片保存在{"+dirPath+"}目录中");
                //为防止重名使用时间戳从新命名
                String filename = "image" + Long.toString(System.currentTimeMillis()) + "." + FilenameUtils.getExtension(upfile.getOriginalFilename());   ;
                String filePath = dirPath + "/" + filename;
                upfile.transferTo(new File(filePath));//转存文件

                //组装返回值
                imageState.setState("SUCCESS");
                imageState.setOriginal(upfile.getOriginalFilename());
                imageState.setSize(Long.toString(upfile.getSize()));
                imageState.setTitle(filename);
                imageState.setType(upfile.getContentType());
                String url = request.getScheme() +"://" + request.getServerName()  + ":" +request.getServerPort() + request.getContextPath() + "/images/" + filename;
                imageState.setUrl(url);
                return mapper.writeValueAsString(imageState);
            }else{
                imageState.setState("无匹配的action类型");
                return mapper.writeValueAsString(imageState);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
package pub.lichao.ueditor.controller;

/**
 * Ueditor 图片返回值
 */
public class ImageState {
    /**
     * 上传状态 上传成功时必须返回"SUCCESS",失败时能够返回错误提示
     */
    private String state;

    /**
     * 上传的原文件名
     */
    private String original;

    /**
     * 文件大小
     */
    private String size;

    /**
     * 上传后的新文件名
     */
    private String title;

    /**
     * 文件类型
     */
    private String type;

    /**
     * 图片访问地址
     */
    private String url;

    ... get set 方法 ...
}

 

访问图片

图片上传成功后要给前台返回一个图片的访问地址,图片才可以正常在插件中展现。这里提供有一个访问项目中图片的类用于本例子使用。若是是使用文件服务器就不用此部分代码了,直接使用服务器提供的url返回给前台展现便可。

package pub.lichao.ueditor.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.nio.file.Paths;

@Controller
public class ImageController {

    private final ResourceLoader resourceLoader;

    @Autowired
    public ImageController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    /**
     * 访问图片
     * @param imagename
     * @param request
     * @return
     */
    @RequestMapping(value = "/images/{imagename:.+}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<?> images(@PathVariable String imagename,HttpServletRequest request) {
        try {
            String dirPath = request.getSession().getServletContext().getRealPath("/images");
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(dirPath, imagename).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
}

 

其实图片上传是一个比较容易实现的功能,此文但愿对你们有帮助。

相关文章
相关标签/搜索