WangEditor富文本編輯器圖片上傳踩坑之路

        最近由於業務需求,需要用到富文本編輯器,找尋了好久,起初想使用百度的ueditor,但在使用的過程中實在是遇到了太多的坑,於是另外鎖定了一款富文本編輯器——wangEditor。這是一款輕量級的富文本編輯器,比起百度的ueditor,這款編輯器的界面更加簡單,文檔也很詳細。對於需求不是很高的功能來說,這款編輯器實在是不二之選。

一、wangEditor的基本顯示demo

這個部分非常簡單,官網文檔也寫得非常詳細,直接參考官網即可

附上文檔地址:https://www.kancloud.cn/wangfupeng/wangeditor3/335769

       下載地址:https://github.com/wangfupeng1988/wangEditor/releases 

編輯器效果如下:

二、圖片上傳後臺接口編寫

後臺用到的是springboot+mybatis+mysql,爲了方便測試,圖片上傳後是直接放在本地服務器。

2.1、Service層代碼

public interface IImgUploadService {

    String imgUpload(String imgPath);
}



@Service("iImgUploadService")
public class ImgUploadServiceImpl implements IImgUploadService {

    @Autowired
    private ImageUploadMapper imageUploadMapper;

    private static Logger logger = LoggerFactory.getLogger("ImgUploadServiceImpl.class");


    /**
     * 存儲上傳圖片的路徑
     * @param
     * @return
     */
    public String imgUpload(String imgPath){

        ImageUpload upload = new ImageUpload();
        upload.setImgpath(imgPath);
        // 一定要加非空判斷,否則會報空指針異常
        if(upload.getImgpath() == null){
            return "圖片地址爲空";
        }
//        logger.error("向數據庫中存儲的路徑爲:" + upload.getImgpath());
//        logger.error("傳遞過來的imgPath參數爲:" + imgPath);
//        logger.error(upload.toString());
        int rowCount = imageUploadMapper.insertImgPath(upload.getImgpath());
        logger.error(rowCount + "");
        if(rowCount > 0){
            return "圖片地址存儲成功";
        }
        return "圖片地址存儲失敗";
    }
}

2.2、Controller層代碼

public class TestController {

    private static final Logger logger = LoggerFactory.getLogger("TestController.class");
    private final ResourceLoader resourceLoader;
    @Autowired
    private IImgUploadService iImgUploadService;
    @Value("${web.upload-path}")
    private String path;
    @Value("${server.port}")
    private String port;

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

    /**
     * @param file 要上傳的文件
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    public Map<String, String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        Map<String,String>  map=new HashMap<>();

        String filePath = request.getSession().getServletContext().getRealPath(path);

        //生成隨機字符串,用於圖片命名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        // 獲得文件類型
        String fileType = file.getContentType();
        // 獲得文件後綴名稱
        String imageName = fileType.substring(fileType.indexOf("/") + 1);
        // 原名稱
//        String fileName = file.getOriginalFilename();
        // 新名稱
        String newFileName = uuid + "." + imageName;

        System.out.println(imageName);

        try {
            FileUtils.upload(file.getBytes(), filePath, newFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 拼接圖片url
        String imgHost = "http://127.0.0.1:" + port;
        String imgUploadPath = path;
        String imgName = newFileName;
        String imgPath = imgHost + imgUploadPath + imgName;
        iImgUploadService.imgUpload(imgPath);
        map.put("url",imgPath);
        return map;

    }

    /**
     * 跳轉到文件上傳頁面
     *
     * @return
     */
    @RequestMapping("test")
    public String toUpload() {
        return "ttt";
    }

2.3、前端HTML代碼

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>ueditor-demo</title>
    <script th:src="@{${#httpServletRequest.getContextPath()}+'/js/jquery-1.7.1.min.js'}"></script>
    <script th:src="@{${#httpServletRequest.getContextPath()}+'/js/wangEditor.min.js'}"></script>

</head>
<body>
<h2>wangEditor</h2>

<div id="editor">
    <p>歡迎使用 <b>wangEditor</b> 富文本編輯器</p>
</div>

<!-- 注意, 只需要引用 JS,無需引用任何 CSS !!!-->
<script type="text/javascript" src="/wangEditor.min.js"></script>
<script type="text/javascript">
    var E = window.wangEditor;
    var editor = new E('#editor');

    //開啓debug模式
    editor.customConfig.debug = true;
    // 關閉粘貼內容中的樣式
    editor.customConfig.pasteFilterStyle = false
    // 忽略粘貼內容中的圖片
    editor.customConfig.pasteIgnoreImg = true
    // 使用 base64 保存圖片
    //editor.customConfig.uploadImgShowBase64 = true


    editor.customConfig.uploadFileName = "file";
    editor.customConfig.uploadImgServer = '/fileUpload';
    editor.customConfig.debug = true;

    //自定義上傳圖片事件
    editor.customConfig.uploadImgHooks = {
        before: function (xhr, editor, files) {

        },
        success: function (xhr, editor, result) {
            console.log("上傳成功");
        },
        fail: function (xhr, editor, result) {
            console.log("上傳失敗,原因是" + result);
        },
        error: function (xhr, editor) {
            console.log("上傳出錯");
        },
        timeout: function (xhr, editor) {
            console.log("上傳超時");
        },
        customInsert: function (insertImg, result, editor) {
            // 圖片上傳並返回結果,自定義插入圖片的事件(而不是編輯器自動插入圖片!!!)
            // insertImg 是插入圖片的函數,editor 是編輯器對象,result 是服務器端返回的結果

            // 舉例:假如上傳圖片成功後,服務器端返回的是 {url:'....'} 這種格式,即可這樣插入圖片:
            var url = result.url;
            insertImg(url)

            // result 必須是一個 JSON 格式字符串!!!否則報錯
        }

    };
    // 或者 var editor = new E( document.getElementById('editor') )
    editor.create()
</script>

</body>

</html>

2.4、效果展示

 

三、踩坑經歷

做的是一個小demo所以代碼很簡單。下面是我要說的重點,我的踩坑經歷。

3.1、上傳圖片的參數問題

如果後臺自定義的上傳文件的參數,如圖

那麼前端js中就得添一句:

editor.customConfig.uploadFileName = 'file'

用於指定參數名,否則前端會出現“400”的錯誤。

3.2、圖片上傳的接口配置

在這裏我被官網的文檔給坑了一把,也許是我自己沒理解清楚吧,唉!文檔中如下圖所說配置

配置地址用的是

editor.config.uploadImgUrl = '/upload';

然而我用這個確怎麼也無法成功,編輯器都無法創建,後臺更改爲

// 配置服務器端地址
    editor.customConfig.uploadImgServer = '/upload'

成功創建編輯器。

3.3、後臺數據返回與編輯器內部圖片顯示

       如果我們通過上面配置的接口成功將圖片上傳至服務器了,現需要在編輯器裏將剛上傳的圖片顯示在編輯器裏面。那麼後臺需要返回圖片的url,格式如http://localhost:8011/uploadfiles/5168898981064558.jpeg,在瀏覽器中輸入該url,然後回車,要能得到剛纔上傳的圖片

例如:

接着要想讓此圖片在編輯器裏面顯示,還需要在前端自定義插入圖片的事件,因爲編輯器是不會自動插入圖片的,貼出該事件的代碼:

customInsert: function (insertImg, result, editor) {
      
        // insertImg 是插入圖片的函數,editor 是編輯器對象,result 是服務器端返回的結果

        // 舉例:假如上傳圖片成功後,服務器端返回的是 {url:'....'} 這種格式,即可這樣插入圖片:
        var url = result.url
        insertImg(url)

        }

注意:result 必須是一個 JSON 格式字符串!!!否則報錯

 

最後貼出demo的完整代碼地址:https://gitee.com/1697923044/springboot-wangEditor

1、項目默認將圖片上傳到本地路徑,如果需要上傳到服務器路徑直接在項目中進行修改即可,不要忘了修改存儲到數據庫中的路徑。

2、項目沒有使用任何圖片上傳控件或插件,原生springBoot實現,簡單易上手。

3、項目使用Maven進行構建,朋友們在導入項目時不要導錯了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章