vue3wangeditor上传图片
时间: 2023-11-20 17:05:20 浏览: 138
为了在Vue3中使用wangeditor并实现上传图片功能,需要进行以下步骤:
1. 安装wangeditor和axios
```shell
npm install wangeditor axios --save
```
2. 在组件中引入wangeditor和axios
```javascript
import WangEditor from 'wangeditor'
import axios from 'axios'
```
3. 在组件的mounted钩子函数中初始化wangeditor
```javascript
mounted() {
const editor = new WangEditor('#editor')
editor.config.uploadImgServer = '/upload' // 上传图片的接口地址
editor.config.uploadFileName = 'file' // 上传图片的文件名
editor.config.uploadImgHeaders = { // 上传图片时需要携带的请求头
Authorization: 'Bearer ' + localStorage.getItem('token')
}
editor.config.uploadImgHooks = { // 上传图片的回调函数
customInsert: function (insertImg, result, editor) {
if (result.code === 200) {
insertImg(result.data.url)
} else {
alert('上传失败')
}
}
}
editor.create()
}
```
4. 在组件中添加一个textarea元素,并将其id设置为editor
```html
<template>
<div>
<textarea id="editor"></textarea>
</div>
</template>
```
5. 在后端实现上传图片的接口,并将其地址填写到第3步中的uploadImgServer属性中
```javascript
const express = require('express')
const multer = require('multer')
const app = express()
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname)
}
})
const upload = multer({ storage: storage })
app.post('/upload', upload.single('file'), (req, res) => {
const file = req.file
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send({
code: 200,
data: {
url: 'http://localhost:3000/' + file.path
}
})
})
app.listen(3000, () => {
console.log('Server started on port 3000')
})
```
阅读全文