本文主要是介绍vue小记——上传图片小组件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
个人笔记
前端:
<template><el-uploadclass="avatar-uploader"name="image"action="http://127.0.0.1:3000/api/image/upload":show-file-list="false":headers="headerObj":data="DataForm":on-success="handleAvatarSuccess":before-upload="beforeAvatarUpload":on-preview="handlePictureCardPreview"><img v-if="imageUrl" :src="imageUrl" class="avatar" /><i v-else class="el-icon-plus avatar-uploader-icon"></i></el-upload>
</template><script>
export default{date(){return:{headerObj: {Authorization: localStorage.getItem("mytoken"),},imageUrl:"",DataForm: {},}},methods:{//控制图片预览窗口的显示与隐藏beforeAvatarUpload(file) {this.DataForm = {code: this.ruleForm.code,user: this.$store.getters.user.name,};console.log(this.DataForm);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;},handleAvatarSuccess(res, file) {if (res.status == "1") return this.$message.error(res.message);this.imageUrl = res.imageUrl;this.$message.success("修改头像成功");console.log(this.DataForm);},handlePictureCardPreview(file) {this.dialogImageUrl = file.url;this.dialogVisible = true;},}
}</script>
后端(node.js):
router:
const express= require('express')
const router=express.Router()
const imageHandler=require('../router_handler/images.js')
const multer=require('multer')//磁盘存储引擎,可以控制文件的存储,省略的话这些文件会保存在内存中,不会写入磁盘
const storage=multer.diskStorage({destination:(req,res,cb)=>{//控制文件的存储路径cb(null,'public/images')},filename:function(req,file,cb){cb(null,file.fieldname + '-' + Date.now() + '-' + file.originalname)}
})
const upload=multer({storage:storage})router.post('/upload',upload.single('image'),imageHandler.upload)module.exports=router
router_handler:
const db = require("../db/index");const imageHandler = {upload: (req, res) => {const sql = 'update proj set image=? where code=? and user=?;'const imageUrl = `http://127.0.0.1:3000/images/${req.file.filename}`// console.log(avatarUrl);// 执行sql语句db.query(sql, [imageUrl, req.body.code,req.body.user], (err, results) => {// sql语句执行错误if(err) return res.cc(err)// sql语句执行成功,但影响的条数部位1属于执行失败if(results.affectedRows !== 1) return res.cc('上传图片失败!')// 更换头像成功res.json({msg:'上传成功',imageUrl:imageUrl})})},
};module.exports = imageHandler;
一定要加上这句
app.use(express.static('public'))
这篇关于vue小记——上传图片小组件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!