前言
一直想寫這篇文章,無奈由于要考試的原因,一直在復習芳来,拖延到現(xiàn)在才寫??含末,之前用 node 的 express 框架寫了個小項目,里面有個上傳圖片的功能即舌,這里記錄一下如何實現(xiàn)(我使用的是 ejs)??
思路
-
首先佣盒,當用戶點擊上傳頭像,更新頭像的時候顽聂,將頭像上傳到項目的一個文件夾里面(我是存放在項目的
public/images/img
里面)肥惭,并且將圖像名重命名(可以以時間戳來命名)。 -
同時圖片在項目的路徑插入到用戶表的當前用戶的
userpicturepath
里面 - 然后更新用戶的 session紊搪,將圖片里面的路徑賦值給 session 的里面的
picture
屬性里面 -
<img>
的src
獲取到當前用戶的session里面的picture
的值蜜葱,最后動態(tài)刷新頁面頭像就換成了用戶上傳的頭像了
實現(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, // 不設置內(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'; //設置編碼
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);
});
}
});
});