欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

利用nodeJS+vue圖片上傳實(shí)現(xiàn)更新頭像的過程

 更新時間:2022年04月26日 12:17:10   作者:用戶9377671805446  
Vue是一套構(gòu)建用戶界面的框架,最近工作中遇到了一個需求,需要做一個更新頭像的通能,下面這篇文章主要給大家介紹了關(guān)于利用nodeJS+vue圖片上傳的相關(guān)資料,需要的朋友可以參考下

思路:

前端通過el-upload將圖片傳給后端服務(wù),后端通過formidable中間件解析圖片,生成圖片到靜態(tài)資源文件夾下(方便前端直接訪問),并將圖片路徑返回給前端,前端拿到圖片路徑即可渲染頭像。

1、前端準(zhǔn)備

前端采用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">點(diǎn)擊修改頭像</i>
</el-upload>

action:必選參數(shù),上傳的地址,這里是http://localhost:3007/api/upload 表示后端服務(wù)地址

before-upload:上傳文件之前的鉤子,主要用于文件上傳前的校驗,可以限制文件上傳的大小及格式。這里設(shè)置頭像只能上傳png、jpg格式,圖片大小不能超過2M,具體設(shè)置方法如下:

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:上傳時附帶的額外參數(shù).這里將用戶名、用戶ID傳給后端服務(wù),用于生成圖片時拼接圖片名,保證圖片名唯一性,具體如下:

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()
}

點(diǎn)擊用戶頭像上傳圖片:

2、node后端服務(wù)

需要用到的依賴:

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

具體代碼如下:

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

//引入數(shù)據(jù)庫模塊存儲用戶當(dāng)前的頭像地址
const db = require('../db/index');

// 設(shè)置運(yùn)行跨域
const cors = require('cors')
app.use(cors())

// 處理圖片文件中間件
var formidable = require("formidable");
fs = require("fs");

// 暴露靜態(tài)資源
app.use('/public', express.static('public'));

// 上傳圖片服務(wù)
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靜態(tài)資源文件夾下

        // 更新用戶當(dāng)前頭像地址信息
        const sql = 'update ev_users set user_pic = ? where id = ?';
        db.query(sql, [fullFileName, user_id], function (err, results) {
            // 執(zhí)行 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創(chuàng)建端口號為3007的服務(wù)。引入formidable中間件存儲圖片,存儲后將圖片路徑返回給前端。并將用戶頭像路徑信息存入用戶表,和用戶綁定,這樣每次用戶登錄后就能得到當(dāng)前用戶的頭像路徑信息,從而渲染自己的頭像。formidable解析后,得到用戶上傳的信息:fields除了圖片外的信息,files圖片信息。

上傳后的效果:

總結(jié)

到此這篇關(guān)于利用nodeJS+vue圖片上傳的文章就介紹到這了,更多相關(guān)nodeJS vue圖片上傳內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論