wangEditor之上传图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014248473/article/details/88416550

一、环境介绍

wangEditor 3
springBoot 1.5.3.RELEASE

二、前端

  1. html
<script src="/thirdparty/wangEditor.min.js"></script>

<div id="editor">
    <p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>
</div>
  1. js
var E = window.wangEditor;
var editor = new E('#editor');
editor.customConfig.uploadImgServer = '/articleImg/uploadImg';
editor.customConfig.uploadFileName = 'img';
editor.create();

三、后端

  1. Controller
@Controller
@RequestMapping("/articleImg")
public class ArticleImgController {

    @Autowired
    private ArticleImgService articleImgService;

    @RequestMapping("/uploadImg")
    @ResponseBody
    public Map<String,Object> uploadImg(@RequestParam("img") List<MultipartFile> list){
        Map<String,Object> map = new HashMap<String, Object>();
        int errno = 1;//错误代码
        String[] data = new String[0];//存放数据
        try {
            data = articleImgService.uploadImg(list);
            errno = 0;
        }catch (Exception e){
            errno = 1;
            e.printStackTrace();
        }
        map.put("errno",errno);
        map.put("data",data);
        return map;
    }
}
  1. Service
public String[] uploadImg(List<MultipartFile> list) throws Exception {
    String imgUploadAbsolutePath = ResourceUtils.getURL("classpath:").getPath() + "static";
    log.info("imgUploadAbsolutePath: " + imgUploadAbsolutePath);
    String imgUploadRelativePath = "/uplaod/articleimg/";
    String finalPath = imgUploadAbsolutePath + imgUploadRelativePath;  //绝对路径 + 相对路径
    File finalPathFile = new File(finalPath);
    if(!finalPathFile.exists()){
        finalPathFile.mkdirs();
    }
    log.info("finalPath: " + finalPath);
    String[] urlData = new String[5];
    int index = 0;
    for(MultipartFile img : list) {
        String fileName = img.getOriginalFilename();
        if(fileName == "") {
            continue;
        }
        //为了保证文件名不一致,因此文件名称使用当前的时间戳和4位的随机数,还有原始文件名组成
        //觉得实际的企业开发不应当使用原始文件名,否则上传者使用一些不好的名字,对于下载者就不好了.
        //这里为了调试方便,可以加上.
        String finalFileName =  (new Date().getTime()) + Math.round(Math.random() * 1000)  //文件名动态部分
                + fileName; //文件名 原始文件名
        File newfile = new File( finalPath + finalFileName);
        log.info("newfile path: " + newfile.getAbsolutePath());
        //保存文件到本地
        img.transferTo(newfile);

        //持久化到数据库
        ArticleImg articleImg = new ArticleImg();
        articleImg.setImgName(finalFileName);
        articleImg.setImgUrl(imgUploadRelativePath + finalFileName);
        articleImg.setUploadTime(new Date());
        insertSelective(articleImg);

        //这里的路径是项目路径+文件路径+文件名称
        //这么写不是规范的做法,项目路径应是放在前端处理,只需要发送相对路径和文件名称即可,项目路径由前端加上.
        urlData[index++] = imgUploadRelativePath + finalFileName;
        log.info("urlData["+(index-1)+"]: " + urlData[index-1]);
    }
    return urlData;

猜你喜欢

转载自blog.csdn.net/u014248473/article/details/88416550