nodeJS+vue图片上传,更新头像

1,419 阅读2分钟

思路:前端通过el-upload将图片传给后端服务,后端通过formidable中间件解析图片,生成图片到静态资源文件夹下(方便前端直接访问),并将图片路径返回给前端,前端拿到图片路径即可渲染头像。

1、前端准备

前端采用vue的el-upload组件,具体用法见官方API。使用代码如下

<!--头像上传-->
<el-upload
  class="avatar-uploader"
  action="http://localhost:3007/api/upload"
  :data= this.avatarForm
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="avatar-uploader-icon">点击修改头像</i>
</el-upload>

action:必选参数,上传的地址,这里是http://localhost:3007/api/upload 表示后端服务地址

before-upload:上传文件之前的钩子,主要用于文件上传前的校验,可以限制文件上传的大小及格式。这里设置头像只能上传png、jpg格式,图片大小不能超过2M,具体设置方法如下:

beforeAvatarUpload(file) {
  console.log(file.type)
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!(isJPG || isPNG)) {
    this.$message.error('上传头像图片只能是 JPG 格式!')
  }
  if (!isLt2M) {
    this.$message.error('上传头像图片大小不能超过 2MB!')
  }
  return (isPNG || isJPG) && isLt2M
}

on-success:文件上传成功时的钩子,这里接受图片路径成功后,拼接成正确的图片路径,并将路径赋值给src,具体如下:

handleAvatarSuccess(res, file) {
  if (res.status === '1') return this.$message.error(res.message)
  this.imageUrl = `http://localhost:3007/public/${res.srcurl}`  //拼接路径
  this.$message.success('修改头像成功')
}

data:上传时附带的额外参数.这里将用户名、用户ID传给后端服务,用于生成图片时拼接图片名,保证图片名唯一性,具体如下:

mounted() {
  this.name = window.sessionStorage.getItem('username')
  this.user_pic = window.sessionStorage.getItem('user_pic')
  this.user_id = window.sessionStorage.getItem('user_id')
  this.avatarForm = {
    name: this.name, // 用户名
    user_id: this.user_id // 用户ID
  }
  this.getUserAvata()
}

点击用户头像上传图片:

image.png

2、node后端服务

需要用到的依赖:

"dependencies": {
  "express": "^4.16.2",
  "cors": "^2.8.5",
  "formidable": "^1.1.1"
}

具体代码如下:

var express = require('express');
var app = express();

//引入数据库模块存储用户当前的头像地址
const db = require('../db/index');

// 设置运行跨域
const cors = require('cors')
app.use(cors())

// 处理图片文件中间件
var formidable = require("formidable");
fs = require("fs");

// 暴露静态资源
app.use('/public', express.static('public'));

// 上传图片服务
app.post('/upload', function (req, res) {
    var info = {};
    // 初始化处理文件对象
    var form = new formidable.IncomingForm();
    form.parse(req, function(error, fields, files) {
        if(error) {
            info.status = '1';
            info.message = '上传头像失败';
            res.send(info);
        }
        // fields 除了图片外的信息
        // files 图片信息
        console.log(fields);
        console.log(files);
        var user_id = parseInt(fields.user_id);
        var fullFileName = fields.name + user_id + files.file.name;// 拼接图片名称:用户名+用户ID+图片名称
        fs.writeFileSync(`public/${fullFileName}`, fs.readFileSync(files.file.path)); // 存储图片到public静态资源文件夹下

        // 更新用户当前头像地址信息
        const sql = 'update ev_users set user_pic = ? where id = ?';
        db.query(sql, [fullFileName, user_id], function (err, results) {
            // 执行 SQL 语句失败
            if (err) {
                info.status = '1';
                info.message = '上传失败';        
                return (info)
            }
            info.status = '0';
            info.message = 'success';
            info.srcurl = fullFileName;
            res.send(info);
        });
    });
});

var server = app.listen(3007, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://localhost:%s', port);
});

分析:通过express创建端口号为3007的服务。引入formidable中间件存储图片,存储后将图片路径返回给前端。并将用户头像路径信息存入用户表,和用户绑定,这样每次用户登录后就能得到当前用户的头像路径信息,从而渲染自己的头像。formidable解析后,得到用户上传的信息:fields除了图片外的信息,files图片信息。

上传后的效果:

image.png