vue小记——上传图片小组件

个人笔记

前端:

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'))
相关推荐
小峰编程32 分钟前
Python函数——万字详解
linux·运维·服务器·开发语言·前端·网络·python
海盐泡泡龟1 小时前
Javascript本地存储的方式有哪些?区别及应用场景?(含Deep Seek讲解)
开发语言·javascript·ecmascript
11054654012 小时前
23、电网数据管理与智能分析 - 负载预测模拟 - /能源管理组件/grid-data-smart-analysis
前端·能源
开发者小天2 小时前
React中startTransition的使用
前端·react.js·c#
@PHARAOH3 小时前
WHAT - 缓存命中 Cache Hit 和缓存未命中 Cache Miss
前端·缓存
计算机学姐3 小时前
基于SpringBoot的小型民营加油站管理系统
java·vue.js·spring boot·后端·mysql·spring·tomcat
Elastic 中国社区官方博客3 小时前
JavaScript 中使用 Elasticsearch 的正确方式,第一部分
大数据·开发语言·javascript·数据库·elasticsearch·搜索引擎·全文检索
万物得其道者成3 小时前
从零开始创建一个 Next.js 项目并实现一个 TodoList 示例
开发语言·javascript·ecmascript
海天胜景3 小时前
无法加载文件 E:\Program Files\nodejs\npm.ps1,因为在此系统上禁止运行脚本
前端·npm·node.js
MingT 明天你好!3 小时前
在vs code 中无法运行npm并报无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查
前端·npm·node.js·visual studio code