springboot + thymeleaf + mybatis + ueditor

来源:互联网 发布:命令者模式 java 编辑:程序博客网 时间:2024/06/07 01:33

前面讲了简单的ueditor搭建,今天记录一下上传和图片空间的开发:
由于springboot不好放图片,放上去也会让后面我的打的包越来越大,这不科学,所以用项目外的图片服务器,这路我用的七牛云,当然也可以用其他的图片服务器比如fastDFS什么的,反正能实现就好
废话不多说,直接晒代码.
先导入七牛云依赖
<!--七牛云存储-->
<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>7.2.6</version>
    <scope>compile</scope>
</dependency>


<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>happy-dns-java</artifactId>
    <version>0.1.4</version>
    <scope>compile</scope>
</dependency>
官网上是要导入很多包的,但是其他的包我都有,避免jar包冲突,我就没有导,

操作数据库我就不讲了,我就建了一个这样的数据库:
CREATE TABLE `t_ueditor_imgspace` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `url` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '图片地址',
  `c_time` datetime DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;




用来记录上传的图片,好返回给图片空间.




然后我根据官网的文档搞了一个七牛云的工具类:
package utils;


import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;


public class QiniuUtil {
    public static final String preUrl = ""; //七牛云给的空间的前缀地址
    private static final String accessKey = "";
    private static final String secretKey = "";
    private static final String bucket = "";   //空间名


    /**
     * 上传到七牛云
     *
     * @param file
     * @return
     */
    public static String upload(MultipartFile file) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        String res = null;
        try {
            Response response = uploadManager.put(file.getBytes(), key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            res = putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            ex.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }


    /**
     * 获取图片列表
     */
    public static void getImgList() {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //文件名前缀
        String prefix = "";
        //每次迭代的长度限制,最大1000,推荐值 1000
        int limit = 1000;
        //指定目录分隔符,列出所有公共前缀(模拟列出目录效果)。缺省值为空字符串
        String delimiter = "";
        //列举空间文件列表
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                System.out.println(item.key);
                System.out.println(item.hash);
                System.out.println(item.fsize);
                System.out.println(item.mimeType);
                System.out.println(item.putTime);
                System.out.println(item.endUser);
            }
        }
    }


}
里面的参数注册了七牛云,创建存储空间会给你的,自己天上去吧.
然后看看控制器的操作:
package com.anh.admin.controller;


import com.anh.admin.entity.UeditorImg;
import com.anh.admin.service.UediortImgService;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import utils.QiniuUtil;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.util.*;


import static com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.ROOT;




@Controller  //打杂的控制器
public class CommonController {


    @javax.annotation.Resource
    UediortImgService uediortImgService;


    public static final String ROOT = "upload";


    private final ResourceLoader resourceLoader;


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


    //ueditr后端配置
    @ResponseBody
    @RequestMapping(value = "ueditor.py")
    public String ueditor(@RequestParam(value = "action", required = true) String action,
                          @RequestParam(value = "noCache", required = false) String nocache,
                          @RequestParam(value = "upfile", required = false) MultipartFile[] files,
                          @RequestParam(value = "start",required = false) Integer start,
                          @RequestParam(value = "size",required = false) Integer size,
                          HttpServletRequest request, HttpServletResponse response) {
        String callback = null;
        switch (action) {
            //获取配置
            case "config":
                System.out.println("config");
                try {
                    response.setContentType("application/json;charset=utf-8");
                    Resource resource = new ClassPathResource("ueditorConfig.json");
                    File file = resource.getFile();
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        stringBuilder.append(line);
                    }
                    callback = stringBuilder.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                    callback = "error";
                }
                break;
            //上传图片
            case "upload":
                System.out.println("upload");
                Map<String,String> map = new HashMap<>();
                List<UeditorImg> urls = new ArrayList<>();
                for (MultipartFile file : files) {
                    UeditorImg ueditorImg = new UeditorImg();
                    ueditorImg.setUrl(QiniuUtil.preUrl+QiniuUtil.upload(file));
                    ueditorImg.setcTime(new Date(System.currentTimeMillis()));
                    urls.add(ueditorImg);
                }
                try {
                    uediortImgService.insertList(urls);
                    map.put("state","SUCCESS");
                }catch (Exception e){
                    e.printStackTrace();
                }
                callback = new Gson().toJson(map);
                break;
            //图片空间
            case "listimage":
                Map<String,Object> map1 = new HashMap<>();
                PageHelper.startPage(start,size);
                List<UeditorImg> list = uediortImgService.selectAll();
                map1.put("state","SUCCESS");
                map1.put("list",list);
                map1.put("start",start);
                map1.put("size",size);
                callback = new Gson().toJson(map1);
                break;
            default:
                break;
        }
        return callback;
    }
}
这样就完成了,讲的比较粗糙,其实我主要是自己记录一下,代码就这些,建议多读一下ueditor和七牛云的文档,里面都有的。后面还要弄一下cdn加速,这个我就不记录了,结果如下图。














原创粉丝点击