使用vue mavon-editor 上传图片事件如何将图片传入后端express,express后端只使用fs模块写入图片
时间: 2024-06-07 18:12:03 浏览: 10
首先,在前端使用mavon-editor上传图片时,会调用一个接口用于上传图片。你可以在该接口中将图片转换为base64编码,然后将编码传递给后端express。下面是一个简单的示例代码:
前端代码:
```javascript
<template>
<div>
<mavon-editor v-model="content" :subfield="true" @imgAdd="onImgAdd"></mavon-editor>
</div>
</template>
<script>
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
export default {
components: {
mavonEditor
},
data() {
return {
content: ''
}
},
methods: {
onImgAdd(img) {
const reader = new FileReader()
reader.readAsDataURL(img)
reader.onload = () => {
const base64 = reader.result.split(',')[1]
this.uploadImage(base64)
}
},
async uploadImage(base64) {
try {
const res = await this.$axios.post('/api/upload', { image: base64 })
console.log(res)
} catch (error) {
console.log(error)
}
}
}
}
</script>
```
在上面的代码中,我们首先使用mavon-editor组件渲染编辑器,并监听imgAdd事件。当用户在编辑器中上传图片时,就会触发该事件,并传递一个File对象。
在onImgAdd方法中,我们将图片转换为base64编码,然后调用uploadImage方法将图片上传到后端。
后端代码:
```javascript
const express = require('express')
const app = express()
const fs = require('fs')
app.use(express.json())
app.post('/api/upload', (req, res) => {
const base64Image = req.body.image
const imageName = Date.now() + '.png'
const imagePath = './uploads/' + imageName
fs.writeFile(imagePath, base64Image, 'base64', (err) => {
if (err) {
console.log(err)
res.status(500).send({
message: 'Error uploading image'
})
} else {
res.send({
message: 'Image uploaded successfully'
})
}
})
})
app.listen(3000, () => {
console.log('Server running on port 3000')
})
```
在上面的代码中,我们首先创建一个express应用程序,并在应用程序中使用express.json中间件解析请求正文。
然后,我们定义了一个POST /api/upload路由,用于上传图片。在该路由中,我们首先从请求正文中获取base64编码的图片,并使用Date.now()生成一个唯一的文件名。然后,我们将文件写入到uploads目录中,并使用回调函数处理错误和成功的情况。
最后,我们启动express应用程序并监听端口3000。现在,当用户在前端上传图片时,图片会被传递给后端,并写入到uploads目录中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)