上传图片nodejs+vue2+mysql

后端:

在入口文件app.js中  使用 中间件,将 目录中的图片托管为静态资源:

app.use('/uploads',express.static('uploads'))

对应数据库操作

...req.body是个扩展运算符 

exports.addArticle = (req, res) => {
    console.log(req.file);
    const path = require('path');
    if (!req.file || req.file.fieldname !== 'cover_img') return res.cc('文章封面是必选参数')
    const articleInfo = {
        ...req.body,
 // 文章封面在服务器端的存放路径
        cover_img: path.join('/uploads', req.file.filename),
        pub_date: new Date(),
        author_id: req.user.id
    }
    console.log( articleInfo)
    const sql = `insert into ev_article set  ? ,is_delete=0`
    const db = require('../db/index')
    db.query(sql, articleInfo, (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('发布文章失败')
        res.cc('发布文章成功', 0)
    })
}

这边记得打印一下

console.log( articleInfo)
cover_img的赋值可以 originalname  这个后面有后缀 但是赋值带不上去

所以推荐使用 filename

filename 在uploads文件里面就没有后缀的jpg

 originalname在uploads文件里面要自己手动添加jpg

一定要一一对应

前端 vue2+elementui

<el-form-item prop="cover_img">
          <img src="@/assets/images/cover.jpg" alt="" srcset="" ref="imgRef">
          <input type="file" name="cover_img" accept="image/gif,image/jpeg,image/jpg,image/png" style="display: none" ref="FileRef" @change="changeCoverFn">
          <el-button type="text" @click="selCoverFn">选择封面</el-button>
</el-form-item>

 这里采用的是点击事件先把选择封面的file隐藏起来 当点击触发点击事件

//让封面窗口出现的点击事件
    selCoverFn() {
      this.$refs.FileRef.click()
    },

这是最后的提交的点击事件 在提交之前要进行一个兜底校验,校验的注意ref 

pubArticleFn(str) {
      this.formDialog.status = str
      //  兜底校验
      this.$refs.DialogRef.validate(async valid => {
        if (valid) {
          const fd = new FormData()
          fd.append('title', this.formDialog.title)
          fd.append('cate_id', this.formDialog.id)
          fd.append('content', this.formDialog.content)
          fd.append('state', this.formDialog.status)
          fd.append('cover_img', this.formDialog.cover_img)
          const {data:res} = await addloadArticleAPI(fd)
          // console.log( addloadArticleAPI(fd))
          if (res.status != 0) return this.$message.error('发布文章失败')
          this.$message.success('发布文章成功')
          //  关闭弹窗
          this.dialogVisible = false
        //  刷新文章列表,再次请求文章列表数据
          this.getArticleListFn()
        } else {
          return false
        }
      })
    },

这里FormData将form表单元素的name与value进行组合,实现表单数据的序列化,从而减少表单元素的拼接,提高工作效率

  • FormData.append()
    向 FormData 中添加新的属性值,FormData 对应的属性值存在也不会覆盖原值,而是新增一个值,如果属性不存在则新增一项属性值。

 接口

export const addloadArticleAPI=(fd)=>{
  return request({
    url:'my/article/add',
    method:'POST',
    data:fd
  })
}

这里fd不是对象 不能用{} 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现一个使用Node.js+Vue+MySQL的客服系统,需要以下几个步骤: 1. 创建一个MySQL数据库,用于存储客户信息和聊天记录; 2. 创建一个Node.js后端,提供API接口,用于客户端和管理端进行数据交互; 3. 创建一个Vue前端,实现在线聊天和管理客户的操作。 下面是一个简单的示例,使用Node.js+Vue+MySQL实现客服系统的具体过程和代码: 1. 创建MySQL数据库 同样的,我们需要创建一个MySQL数据库,用于存储客户信息和聊天记录。可以使用上面的SQL语句来创建。 2. 使用Node.js连接MySQL数据库 安装mysql模块,使用以下代码连接MySQL数据库: ``` const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'customer_service' }); connection.connect(); ``` 3. 创建API接口 在Node.js后端中创建API接口,用于客户端和管理端进行数据交互。可以使用Express框架来创建API接口。 ``` const express = require('express'); const app = express(); // 获取所有客户信息 app.get('/customers', (req, res) => { connection.query('SELECT * FROM customers', (error, results, fields) => { if (error) throw error; res.json(results); }); }); // 根据客户ID获取聊天记录 app.get('/messages/:customerId', (req, res) => { const customerId = req.params.customerId; connection.query('SELECT * FROM messages WHERE customer_id = ?', [customerId], (error, results, fields) => { if (error) throw error; res.json(results); }); }); // 发送聊天消息 app.post('/messages', (req, res) => { const { customerId, sender, message } = req.body; connection.query('INSERT INTO messages (customer_id, sender, message) VALUES (?, ?, ?)', [customerId, sender, message], (error, results, fields) => { if (error) throw error; res.json({ success: true }); }); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` 4. 创建Vue前端 使用Vue框架创建前端界面,实现在线聊天和管理客户的操作。可以使用Vue CLI工具来创建Vue项目。 ``` vue create customer-service ``` 创建成功后,在src目录下创建一个components目录,用于存放Vue组件。 5. 实现客户列表组件 在components目录下创建一个Customers.vue组件,用于显示客户列表。 ``` <template> <div> <table> <thead> <tr> <th>Name</th> <th>Email</th> <th>Phone</th> </tr> </thead> <tbody> <tr v-for="customer in customers" :key="customer.id"> <td>{{ customer.name }}</td> <td>{{ customer.email }}</td> <td>{{ customer.phone }}</td> </tr> </tbody> </table> </div> </template> <script> export default { data() { return { customers: [] }; }, mounted() { fetch('/customers') .then(response => response.json()) .then(customers => { this.customers = customers; }); } }; </script> ``` 6. 实现聊天记录组件 在components目录下创建一个Messages.vue组件,用于显示聊天记录。 ``` <template> <div> <h3>{{ customer.name }}'s Messages</h3> <ul> <li v-for="message in messages" :key="message.id"> <strong>{{ message.sender }}</strong>: {{ message.message }} </li> </ul> <form @submit.prevent="sendMessage"> <input type="text" v-model="message" placeholder="Type your message here"> <button type="submit">Send</button> </form> </div> </template> <script> export default { props: ['customer'], data() { return { messages: [], message: '' }; }, mounted() { fetch(`/messages/${this.customer.id}`) .then(response => response.json()) .then(messages => { this.messages = messages; }); }, methods: { sendMessage() { fetch('/messages', { method: 'POST', body: JSON.stringify({ customerId: this.customer.id, sender: 'customer', message: this.message }), headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(result => { if (result.success) { this.messages.push({ sender: 'customer', message: this.message }); this.message = ''; } }); } } }; </script> ``` 7. 实现客户详情组件 在components目录下创建一个Customer.vue组件,用于显示客户详情。 ``` <template> <div> <h3>{{ customer.name }}</h3> <p>Email: {{ customer.email }}</p> <p>Phone: {{ customer.phone }}</p> <messages :customer="customer"></messages> </div> </template> <script> import Messages from './Messages.vue'; export default { components: { Messages }, props: ['customer'] }; </script> ``` 8. 实现路由配置 在src目录下创建一个router.js文件,用于配置路由。 ``` import Vue from 'vue'; import VueRouter from 'vue-router'; import Customers from './components/Customers.vue'; import Customer from './components/Customer.vue'; Vue.use(VueRouter); const routes = [ { path: '/', component: Customers }, { path: '/customers/:id', component: Customer } ]; const router = new VueRouter({ mode: 'history', routes }); export default router; ``` 9. 启动客户系统 在根目录下创建一个server.js文件,用于启动Node.js后端。 ``` const express = require('express'); const app = express(); const cors = require('cors'); const mysql = require('mysql'); const router = require('./router'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'customer_service' }); connection.connect(); app.use(cors()); app.use(express.json()); app.use(router); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` 在根目录下创建一个vue.config.js文件,用于配置Vue前端的代理服务器。 ``` module.exports = { devServer: { proxy: { '/': { target: 'http://localhost:3000', ws: true, changeOrigin: true } } } }; ``` 最后,在命令行中分别启动Node.js后端和Vue前端: ``` node server.js npm run serve ``` 以上代码仅仅是一个简单的示例,实际的客服系统需要更多的功能和细节处理,例如用户认证、消息推送等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值