Start from scratch, build a simple shopping platform (3): https://blog.csdn.net/time_____/article/details/105411636
Project source code (continuous update): https://gitee.com/DieHunter/myCode/ tree/master/shopping
This article continues from the previous article. After the login interface is built, the user management back-end is written. The main functions include:
Add user, upload avatar
The directory structure is as follows:
First realize the upload avatar function
File upload process: the user selects the file upload, the server reads the file and generates a uniquely named cache file (binary file), returns the file information to the front end, and uploads the file information and user information to the server when the front end submits the form. The server reads the corresponding file, saves it to the public img folder (the image file is generated at this time), and finally saves the image path to the database
Implementation
- Create a new upload folder under the controller folder, add upload.js to the folder for uploading avatars, import the multer module and temporarily store files
const router = require("express").Router(); const Util = require("../../../utils/utils"); var multer = require("multer"); var upload = multer({ dest: "./public/temp",//缓存目录 }); router.post( "/headPic", upload.single("headPic"),//单张图片,图片标识名 Util.checkToken,//验证token (req, res) => { res.send({ result: 1, msg: "上传成功", headPath: req.file, }); } ); module.exports = router;
- Add the routing address of upload.js in the router app.use("/upload", upload);
run the project, do a test, enter the corresponding address and parameters in the postman and click upload, the server returns the cached file information and saves To the cache directory - After adding the upload function, only to ensure that the file is uploaded, but also to convert it into a picture format, so several methods have been added to the utils.js file (to introduce the fs module) , namely:
read the file
Save (write) filestatic readPicFile(_file) { let { path, mimetype } = _file;//获取文件路径和文件类型 let file = fs.readFileSync(path);//将文件转换成二进制 let fileName =//用时间戳加随机数命名文件 new Date().getTime() + parseInt(Math.random() * Math.random() * 1000000) + "." + mimetype.split("/")[1]; this.delPicFile(path);//删除之前的缓存文件 return this.writePicFile(file, fileName);//写文件 }
Delete Filesstatic writePicFile(_file, _fileName) { let fileName = "./public/assets/img/" + _fileName;//文件路径 fs.writeFileSync(fileName, _file); return fileName.split("./")[1]; }
static delPicFile(_path) { fs.unlink(_path, (err) => { if (err) { console.log("删除失败"); } }); }
- After all is completed, the upload file is also completed
Add user function
- Recall the previously written command in the users.js interface (database addition, deletion, modification, query operation)
- Since the increase operation may be mobile user registration, token verification is not added for the time being. Since the mailbox and user name are unique values, the user needs to be searched first
let findRes = await findData(Mod, { $or: [ { mailaddress: res._data.mailaddress, mailurl: res._data.mailurl, }, { username: res._data.username, }, { mailaddress: res._data.username, }, { username: res._data.mailaddress + res._data.mailurl, }, ], }); if (findRes && findRes.length > 0) { res.send({ result: 0, msg: "添加失败,用户已存在", }); Util.delPicFile(res._data.headPic); return; }
- When it is judged that there is no such user, add it to the database
if (res._data.headPic) { res._data.headPic = Util.readPicFile(res._data.headPic || "") || "";//保存头像 } res._data.time = Util.joinDate();//添加时间 res._data.password = Util.createBcrypt(res._data.password);//盐加密 res._data.isactive = true; let addRes = await addData(Mod, res._data); if (addRes) { res.send({ result: 1, msg: "添加成功", }); return; } Util.delPicFile(res._data.headPic); res.send({ result: 0, msg: "添加失败", });
- Test it with postman after completion, the backend prompts that the addition is successful, and the database successfully adds the user
At this point in the article, the avatar is uploaded and the user addition is all realized
to sum up
Front-end and back-end project requests should be throttled (that is, to restrict users from quickly clicking the submit button multiple times). Double insurance on the front-end and back-end can improve user experience and reduce server pressure. Because this project is mainly function-oriented, in details The aspect does not pay much attention, real online projects must add throttling