使用Element的upload组件和nodejs实现图片上传

2 篇文章 0 订阅
1 篇文章 0 订阅
本文详细介绍了如何结合前端Element UI的upload组件和后端Node.js,实现图片上传功能。通过设置上传限制、处理文件及返回文件信息,确保了图片上传的流程完整且符合指定大小限制。同时,提供了相关的HTML、CSS和JavaScript代码示例,以及Node.js的multer中间件处理上传请求的示例。
摘要由CSDN通过智能技术生成

使用Element的upload组件和nodejs实现图片上传

html和css
/*html*/
<el-form-item label="用户头像" prop="imgUrl">
   <el-upload
    class="avatar-uploader"
    action="http://127.0.0.1:8888/upload"
    :show-file-list="false"
    :on-success="uploadSuccess"
    :before-upload="uploadBefore"
    accept="image/*"
   >
   	 <img v-if="imgUrl" :src="imgUrl" class="avatar" />
   	 <i v-else class="el-icon-plus avatar-uploader-icon"></i>
   </el-upload>
</el-form-item>

/*css*/
<style lang="scss" scoped>
.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
js部分
    //图片上传成功
    uploadSuccess(res, file) {
      this.imgUrl = URL.createObjectURL(file.raw);
    },
    //图片上传之前
    uploadBefore(file) {
      let limitMax = 5000 * 1024;
      if (file.size > limitMax) {
        this.$messageTips("大小超出限制");
        return false;
      }
    }
nodejs部分
const express = require("express");
const multer = require("multer");
const fs = require("fs");
const app = new express();

//图片上传
app.post(
  "/upload",
  multer({
    //设置文件存储路径
    dest: "public/image",
  }).array("file", 1),
  function (req, res, next) {
    let files = req.files;
    let file = files[0];
    let fileInfo = {};
    let path = "public/image/" + Date.now().toString() + "_" + file.originalname;
    fs.renameSync("./public/image/" + file.filename, path);
    //获取文件基本信息
    fileInfo.type = file.mimetype;
    fileInfo.name = file.originalname;
    fileInfo.size = file.size;
    fileInfo.path = path;
    res.json({
      code: 200,
      msg: "OK",
      data: fileInfo,
    });
  }
);

参考文章: https://blog.csdn.net/qq_43138078/article/details/90265823.

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值