In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "how to use nodeJS+vue picture upload to update avatar". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to use nodeJS+vue picture upload to update your profile picture".
Train of thought:
The frontend sends the image to the backend service through el-upload, and the backend parses the image through formidable middleware, generates the image under the static resource folder (which is convenient for direct access by the frontend), and returns the image path to the frontend, and the frontend gets the image path to render the avatar.
1. Front-end preparation
The front end uses the el-upload component of vue. For more information, please see the official API. The usage code is as follows
Click to modify the avatar
Action: required parameter. The address to be uploaded. Here, http://localhost:3007/api/upload indicates the address of the backend service.
Before-upload: the hook before uploading files, which is mainly used for checking before uploading files, and can limit the size and format of files uploaded. Here, avatars can only be uploaded in png and jpg format, and the image size cannot exceed 2m. The specific setting method is as follows:
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:上传时附带的额外参数.这里将用户名、用户ID传给后端服务,用于生成图片时拼接图片名,保证图片名唯一性,具体如下: 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()} 点击用户头像上传图片:2. Node backend service
Dependencies to be used:
"dependencies": {"express": "^ 4.16.2", "cors": "^ 2.8.5", "formidable": "^ 1.1.1"}
The specific code is as follows:
Var express = require ('express'); var app = express (); / / introduce the database module to store the user's current profile address const db = require ('.. / db/index'); / / set to run cross-domain const cors = require ('cors') app.use (cors ()) / / process picture file middleware var formidable = require ("formidable"); fs = require ("fs") / / expose static resources app.use ('/ public', express.static ('public')); / / upload image service app.post (' / upload', function (req, res) {var info = {}; / / initialize the file object var form = new formidable.IncomingForm (); form.parse (req, function (error, fields, files) {if (error) {info.status ='1') Info.message = 'failed to upload profile image'; res.send (info);} / fields information except pictures / / files picture information console.log (fields); console.log (files); var user_id = parseInt (fields.user_id); var fullFileName = fields.name + user_id + files.file.name / / stitching image name: user name + user ID+ image name fs.writeFileSync (`user {fullFileName} `, fs.readFileSync (files.file.path)); / / storing the image to the public static resource folder / / updating the user's current avatar address information const sql = 'update ev_users set user_pic =? Where id =?'; db.query (sql, [fullFileName, user_id], function (err, results) {/ / failed to execute SQL statement if (err) {info.status = '1upload; info.message =' upload failed' Return (info)} info.status = '0000; 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);})
Analysis: create a service with port number 3007 through express. Formidable middleware is introduced to store pictures, and after storage, the image path is returned to the front end. And the user avatar path information is stored in the user table and bound with the user, so that each time the user logs in, the avatar path information of the current user can be obtained, thus rendering their own avatar. After formidable parsing, you can get the information uploaded by the user: fields information except pictures, files image information.
The effect after uploading:
At this point, I believe you have a deeper understanding of "how to use nodeJS+vue image upload to update avatars". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.