天天看點

圖檔上傳 基于element-ui upload元件 + NodeJS koa2架構搭建

項目所需

vue 3.0

element-ui

axios

nodejs + koa2

mysql + sequelize

koa-multer 中間件

項目位址

https://github.com/chenfalse/uploadImage

ps: 大家可以下載下傳下來看一下,如果可以的話記得點一個star,謝謝大家!

項目展示

圖檔上傳 基于element-ui upload元件 + NodeJS koa2架構搭建

功能描述

1.圖檔上傳,并且圖檔資訊入庫,重新整理頁面取最新上傳的一條資料

2.清單展示上傳圖檔資訊

3.分頁

核心功能實作

upload 中間件的實作 需要用到koa-multer

/**
 * @description 檔案上傳
 * @author 陳佳兵
 */

const multer = require('koa-multer')
const path = require('path')

//配置
var storage = multer.diskStorage({
  //檔案儲存路徑
  destination: function (req, file, cb) {
      cb(null, 'upload-server/src/public/images/')//path.resolve('public/phoneManageSystem')
  },
  //修改檔案名稱
  filename: function (req, file, cb) {
      var fileFormat = (file.originalname).split(".");  //以點分割成數組,數組的最後一項就是字尾名
      cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
  }
})
//加載配置
var upload = multer({
   storage: storage
})

module.exports = upload
           

路由的實作

const router = require('koa-router')()
const upload = require('../utils/upload')
const { getFileInfo, getFileList } = require('../controller/file')

router.post('/api/uploadImage', upload.single('file'), async (ctx, next) => {
  const {
    destination,
    filename,
    path,
    size,
    mimetype 
  } = ctx.req.file

  ctx.body = await getFileInfo({
    destination,
    filename,
    path,
    size,
    mimetype 
  })
})
           

前端實作

<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="/api/uploadImage"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="require('../../../upload-server/src/public/images/'+ imageUrl)" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>
<script>
export default {
  props: {
    imageUrl: {
      type: String
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = ""
      this.imageUrl = URL.createObjectURL(file.raw)
      this.$emit('handleMounted')
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上傳頭像圖檔大小不能超過 2MB!')
      }
      return isLt2M
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  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>

           

項目位址

uploadImage 圖檔下載下傳

如果可以的話希望大家star一下,謝謝大家!!!

注意

圖檔上傳 基于element-ui upload元件 + NodeJS koa2架構搭建

因為是本地資料庫,下載下傳下來的項目sequelize的執行個體記得改成自己的資料庫位址!

繼續閱讀