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

node簡單實(shí)現(xiàn)一個更改頭像功能的示例

 更新時間:2017年12月29日 09:46:38   作者:Moorez  
本篇文章主要介紹了node簡單實(shí)現(xiàn)一個更改頭像功能的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

前言

一直想寫這篇文章,無奈由于要考試的原因,一直在復(fù)習(xí),拖延到現(xiàn)在才寫🤣,之前用 node 的 express 框架寫了個小項(xiàng)目,里面有個上傳圖片的功能,這里記錄一下如何實(shí)現(xiàn)(我使用的是 ejs)📝

思路

首先,當(dāng)用戶點(diǎn)擊上傳頭像,更新頭像的時候,將頭像上傳到項(xiàng)目的一個文件夾里面(我是存放在項(xiàng)目的public/images/img里面),并且將圖像名重命名(可以以時間戳來命名)。

同時圖片在項(xiàng)目的路徑插入到用戶表的當(dāng)前用戶的 userpicturepath 里面

然后更新用戶的 session,將圖片里面的路徑賦值給 session 的里面的picture屬性里面

<img> 的 src 獲取到當(dāng)前用戶的session里面的 picture 的值,最后動態(tài)刷新頁面頭像就換成了用戶上傳的頭像了

實(shí)現(xiàn)效果

代碼

ejs部分

<img class="nav-user-photo" src="<%= user.picture.replace(/public(\/.*)/, "$1") %>" alt="Photo" style="height: 40px;"/>
<form enctype="multipart/form-data" method="post" name="fileInfo">
  <input type="file" accept="image/png,image/jpg" id="picUpload" name="file">
</form>
<button type="button" class="btn btn-primary" id="modifyPicV">確定</button>

js部分

document.querySelector('#modifyPicV').addEventListener('click', function () {
  let formData = new FormData();
  formData.append("file",$("input[name='file']")[0].files[0]);//把文件對象插到formData對象上
  console.log(formData.get('file'));
  $.ajax({
    url:'/modifyPic',
    type:'post',
    data: formData,
    processData: false, // 不處理數(shù)據(jù)
    contentType: false,  // 不設(shè)置內(nèi)容類型
    success:function () {
      alert('success');
      location.reload();
    },
  })
});

路由部分,使用formidable,這是一個Node.js模塊,用于解析表單數(shù)據(jù),尤其是文件上傳

let express = require('express');
let router = express.Router();
let fs = require('fs');
let {User} = require('../data/db');
let formidable = require('formidable');
let cacheFolder = 'public/images/';//放置路徑
router.post('/modifyPic', function (req, res, next) {
  let userDirPath = cacheFolder + "Img";
  if (!fs.existsSync(userDirPath)) {
    fs.mkdirSync(userDirPath);//創(chuàng)建目錄
  }
  let form = new formidable.IncomingForm(); //創(chuàng)建上傳表單
  form.encoding = 'utf-8'; //設(shè)置編碼
  form.uploadDir = userDirPath; //設(shè)置上傳目錄
  form.keepExtensions = true; //保留后綴
  form.maxFieldsSize = 2 * 1024 * 1024; //文件大小
  form.type = true;
  form.parse(req, function (err, fields, files) {
    if (err) {
      return res.json(err);
    }
    let extName = ''; //后綴名
    switch (files.file.type) {
      case 'image/pjpeg':
        extName = 'jpg';
        break;
      case 'image/jpeg':
        extName = 'jpg';
        break;
      case 'image/png':
        extName = 'png';
        break;
      case 'image/x-png':
        extName = 'png';
        break;
    }
    if (extName.length === 0) {
      return res.json({
        msg: '只支持png和jpg格式圖片'
      });
    } else {
      let avatarName = '/' + Date.now() + '.' + extName;
      let newPath = form.uploadDir + avatarName;
      fs.renameSync(files.file.path, newPath); //重命名
      console.log(newPath)
      //更新表
      User.update({
        picture: newPath
      }, {
        where: {
          username: req.session.user.username
        }
      }).then(function (data) {
        if (data[0] !== undefined) {
          User.findAll({
            where: {
              username: req.session.user.username
            }
          }).then(function (data) {
            if (data[0] !== undefined) {
              req.session.user.picture = data[0].dataValues.picture;
              res.send(true);
            } else {
              res.send(false);
            }
          })
        }
      }).catch(function (err) {
        console.log(err);
      });
    }
  });
});

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論