node簡單實現一個更改頭像功能

Moorez發表於2017-12-28

前言

一直想寫這篇文章,無奈由於要考試的原因,一直在複習,拖延到現在才寫?,之前用 node 的 express 框架寫了個小專案,裡面有個上傳圖片的功能,這裡記錄一下如何實現(我使用的是 ejs)?

思路

  1. 首先,當使用者點選上傳頭像,更新頭像的時候,將頭像上傳到專案的一個資料夾裡面(我是存放在專案的public/images/img裡面),並且將影象名重新命名(可以以時間戳來命名)。
    node簡單實現一個更改頭像功能
  2. 同時圖片在專案的路徑插入到使用者表的當前使用者的 userpicturepath 裡面
  3. 然後更新使用者的 session,將圖片裡面的路徑賦值給 session 的裡面的picture屬性裡面
  4. <img>src 獲取到當前使用者的session裡面的 picture 的值,最後動態重新整理頁面頭像就換成了使用者上傳的頭像了

實現效果

node簡單實現一個更改頭像功能

程式碼

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,  // 不處理資料
        contentType: false,   // 不設定內容型別
        success:function () {
            alert('success');
            location.reload();
        },
    })
});
複製程式碼

路由部分,使用formidable,這是一個Node.js模組,用於解析表單資料,尤其是檔案上傳

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);//建立目錄
    }
    let form = new formidable.IncomingForm(); //建立上傳表單
    form.encoding = 'utf-8'; //設定編碼
    form.uploadDir = userDirPath; //設定上傳目錄
    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);
            });
        }
    });
});
複製程式碼

相關文章