天天看點

React+wangEditor V4富文本編輯器+Node.js實作圖檔上傳

1、安裝wangeditor 4.6.15:

npm i [email protected] -S
           

2、editor.jsx:

import React, { Component } from 'react'
import { Button, Space } from "antd"
import E from 'wangeditor'

export default class Editor extends Component {
    state = {
        content: ""
    }

    editor = {};

    // 擷取html方法1
    getHtml = () => {
        alert(this.state.content)
    }

    // 擷取html方法2
    getHtml1 = () => {
        alert(this.editor.txt.html())
    }

    // 擷取text
    getText = () => {
        alert(this.editor.txt.text())
    }

    componentWillUnmount() {
        this.editor.destroy()
    }

    componentDidMount() {
        this.editor = new E(document.getElementById("wangeditor"));

        // 上傳圖檔
        this.editor.config.uploadImgServer = '/api/upload';
        this.editor.config.uploadFileName = 'myFileName'; // ================這裡是關鍵,背景必須和這裡保持一緻================ 
        this.editor.config.showLinkImg = false;
        this.editor.config.uploadImgTimeout = 60 * 1000;

        this.editor.config.uploadImgHooks = {
            // 上傳圖檔之前
            //before: function (xhr) {
                // console.log(xhr)

                // 可阻止圖檔上傳
                // return {
                //     prevent: true,
                //     msg: '需要提示給使用者的錯誤資訊'
                // }
            //},
            // 圖檔上傳并傳回了結果,圖檔插入已成功
            //success: function (xhr) {
                //console.log('success', xhr)
            //},
            // 圖檔上傳并傳回了結果,但圖檔插入時出錯了
            //fail: function (xhr, editor, resData) {
                //console.log('圖檔上傳并傳回了結果,但圖檔插入時出錯了')
                //console.log(resData)
            //},
            // 上傳圖檔出錯,一般為 http 請求的錯誤
            //error: function (xhr, editor, resData) {
                //console.log('上傳圖檔出錯,一般為 http 請求的錯誤')
                //console.log('error', xhr, resData)
            //},
            // 上傳圖檔逾時
            //timeout: function (xhr) {
                //console.log('timeout')
            //},
            // 圖檔上傳并傳回了結果,想要自己把圖檔插入到編輯器中
            // 例如伺服器端傳回的不是 { errno: 0, data: [...] } 這種格式,可使用 customInsert
            customInsert: function (insertImg, result) {
                // result 即服務端傳回的接口
                console.log('customInsert', result)
                console.log('customInsert')
                console.log(result)

                //var c = result.data[0].imgPath
                insertImg(insertImg);
                //insertImg("https://x0.ifengimg.com/res/2021/21921B99567A8C981CD0503086C2956B68888571_size381_w1200_h856.jpeg") //根據傳回的圖檔路徑,将圖檔插入到頁面中,回顯
            }
        }

        /**一定要建立 */
        this.editor.create()

        this.editor.txt.html('<p>用 JS 設定的内容</p>') // 重新設定編輯器内容
    }

    render() {
        return (
            <div>
                <div id="wangeditor"></div>
                <Space>
                    <Button type="primary" onClick={() => this.getHtml()}>擷取html方法1</Button>
                    <Button type="primary" onClick={() => this.getHtml1()}>擷取html方法2</Button>
                    <Button type="primary" onClick={() => this.getText()}>擷取text方法</Button>
                </Space>
            </div>
        )
    }
}
           

其中:

this.editor.config.uploadImgServer = '/api/upload';
this.editor.config.uploadFileName = 'myFileName'; // 這裡是關鍵,背景必須和這裡保持一緻
           

是關鍵

3、node.js:

const express = require("express")
const fs = require("fs")
const mysql = require("mysql")
const util = require("util")
const { getNow } = require("./tool")

const app = express();

var multer = require('multer');//獲得中間件
var upload = multer({dest:'uploads/'});//指定配置項,這裡指定檔案儲存于目前目錄下的upload子目錄
app.use(upload.single('myFileName'));//運用中間件,并且指明檔案名,此名需要同html input name的檔案名一緻,否則會報錯

const bodyParser = require("body-parser");
const { nextTick } = require("process");
app.use("/static/", express.static("./static/"));
app.use('/node_modules/', express.static('./node_modules/'));
app.engine("html", require("express-art-template"))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// 渲染頁面
app.get("/index", (req, res) => {
    res.render("index.html");
})

app.post("/api/upload", (req, res) => {
    res.jsonp({
        ret: false,
        total: 0,
        rows: [],
        msg: ""
    });
})


app.get("/404", (req, res) => {
    res.render("404.html");
})

// 配置一個全局錯誤進行中間件
app.use(function (err, req, res, next) {
    res.status(500).json({
        err_code: 500,
        message: err.message
    })
})

app.listen(5555, () => {
    console.log("服務啟動成功......");
})
           

其中:

app.use(upload.single('myFileName'));//運用中間件,并且指明檔案名,此名需要同html input name的檔案名一緻,否則會報錯
           
app.post("/api/upload", (req, res) => {
    res.jsonp({
        ret: false,
        total: 0,
        rows: [],
        msg: ""
    });
})
           

是關鍵。

wangEditorV4官網:https://www.wangeditor.com/

繼續閱讀