个人笔记
前端:
javascript
<template>
<el-upload
class="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:
javascript
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:
javascript
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;
一定要加上这句
javascript
app.use(express.static('public'))