React+wangeditor+node富文本處理帶圖片上傳


最近有個需求出現在我的視野中,因為我的另外的博客需要上傳文章,但是我不想每次都在我的數據庫中慢慢的修改格式,所以我另做了一個后台去編輯文本后發送給服務器,那么這里就涉及到兩點,一個是富文本,一個是需要圖片添加之后立即回顯圖片,那么我們現在就進入這個需求的解決吧

首先既然是使用wangeditor這個富文本編輯器,當然第一件事是在你的項目中,下載這個npm包,這里我默認大家已經有新建了一個React項目。

npm install wangeditor --save

下載完成后,需要在自己的組件中導入,可以另起一個組件,這邊我的的代碼是這樣的

import React from 'react';
import Edi from 'wangeditor'
import { Button } from 'antd'
// 這css里面記得導入相關的antd CSS,若不使用antd也可,只是一個效果
import './css/post.css' 
// 我的照片上傳API
const reqUrl = 'http://localhost:5000/upLoadArticlePicture'

let editor1;

export default class Test extends React.Component {
    componentDidMount() {
        this.initEditor()
    }

    initEditor() {
        const elem = this.refs.editor
        const editor = new Edi(elem)

        editor1 = editor

        editor1.customConfig.zIndex = 100
        editor1.customConfig.uploadImgServer = reqUrl
        // 限制一次最多上傳 1 張圖片
        editor1.customConfig.uploadImgMaxLength = 1
        editor1.customConfig.customUploadImg = function (files, insert) {
            // files 是 input 中選中的文件列表
            console.log(files)
            if (files[0]) {
                const formData = new window.FormData()
                formData.append('file', files[0], 'cover.jpg')
                fetch(reqUrl, {
                    method: 'POST',
                    contentType: false,
                    body: formData
                }).then((res) => {
                    return res.json()
                }).then((res) => {
                    if (res.flag) {
                        // 這里你的后台可能不是我這樣的對象屬性,后面會帶我的node后台,請自行參考
                        insert(res.path)
                    } else {
                        console.log(res)
                    }
                })
            } else {
                console.info('請選擇想上傳的圖片')
            }
        }
        // 自定義配置顏色(字體顏色、背景色)
        editor.customConfig.colors = [
            '#000000',
            '#0000ff',
            '#800000',
            '#ff0000',
            '#f47920',
            '#ea66a6',
            '#afdfe4',
            '#563624',
            '#3e4145',
            '#90d7ec',
            '#ffffff'
        ];
    
        editor1.customConfig.menus = [
            'head', // 標題
            'bold', // 粗體
            'fontSize', // 字號
            'fontName', // 字體
            'italic', // 斜體
            'underline', // 下划線
            'strikeThrough', // 刪除線
            'foreColor', // 文字顏色
            'backColor', // 背景顏色
            'link', // 插入鏈接
            'list', // 列表
            'justify', // 對齊方式
            'quote', // 引用
            'emoticon', // 表情
            'image', // 插入圖片
            // 'table', // 表格
            // 'video', // 插入視頻
            // 'code', // 插入代碼
            'undo', // 撤銷
            'redo' // 重復
        ]
        editor1.customConfig.lang = {
            '設置標題': 'Title',
            '字號': 'Size',
            '文字顏色': 'Color',
            '設置列表': 'List',
            '有序列表': '',
            '無序列表': '',
            '對齊方式': 'Align',
            '靠左': '',
            '居中': '',
            '靠右': '',
            '正文': 'p',
            '鏈接文字': 'link text',
            '鏈接': 'link',
            '上傳圖片': 'Upload',
            '網絡圖片': 'Web',
            '圖片link': 'image url',
            '插入視頻': 'Video',
            '格式如': 'format',
            '上傳': 'Upload',
            '創建': 'init'
        }
        editor1.create()
    }
    render() {
        return (
            <div>
                <div ref='editor' />
                <Button onClick={this.post.bind(this)} type="primary">Primary</Button>
            </div>
        );
    }
    post() {
        let html = editor1.txt.html()
// 這里放你的上傳文章代碼,由於各人這邊的邏輯都可能不一樣,就不寫上去了 console.log(html); } }

 大家顯示之后,大概是個這樣的界面

 

但是使用添加照片之后,會發現可能沒有辦法在編輯器里顯示照片?這里需要解釋一下照片添加的邏輯,首先是用戶選擇添加照片,選中照片之后,fetch立即將此照片發送至后台,由后台保存后將保存好的照片名返回,並將此img回顯至編輯器中。

我的node上傳照片代碼,部分導入部分已省略,若需要完整代碼,可以在界面右側聯系我,值得注意的是,使用formidable解析后,jpg文件會直接在你的預設照片目錄有一個很長的隨機名稱,這邊其實我也是使用了較短的名稱進行重命名,大家可以根據自己的需要選擇重命名策略。

const express = require("express");
const listenNumber = 5000;
const app = express();
const bodyParser = require("body-parser");
const http = require('http');//創建服務器的
var formidable = require("formidable");
var path = require("path")
var fs = require("fs")
app.use(express.static('../../upload'))
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());//數據JSON類型

// 上傳圖片
app.post('/upLoadArticlePicture', (req, res, next) => {
    let defaultPath = '../../upload/';
    let uploadDir = path.join(__dirname, defaultPath);
    let form = new formidable.IncomingForm();
    let getRandomID = () => Number(Math.random().toString().substr(4, 10) + Date.now()).toString(36)
    form.uploadDir = uploadDir;  //設置上傳文件的緩存目錄
    form.encoding = 'utf-8';        //設置編輯
    form.keepExtensions = true;     //保留后綴
    form.maxFieldsSize = 2 * 1024 * 1024;   //文件大小
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.locals.error = err;
            res.render('index', { title: TITLE });
            return;
        }
        let filePath = files.file['path'];
        let backName = filePath.split('.')[1]
        let oldPath = filePath.split('\\')[filePath.split('\\').length - 1];
        let newPath = `${getRandomID()}.${backName}`;
        fs.rename(defaultPath + oldPath, defaultPath + newPath, (err) => {//fs.rename重命名
            if (!err) {
                newPath = `http://localhost:${listenNumber}/${newPath}`
                res.json({ flag: true, path: newPath });
            } else {
                res.json({ flag: false, path: '' });
            }
        })
    })
})

然后這里當然還是需要一個正常的文章上傳接口,保存至數據庫,然后就可以在自己的網頁對自己的文章進行編輯了,如下是效果

 

 

 謝謝大家!!!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM