element-ui 和 koa2实现文件上传,并且携带token认证。

1、koa2后台代码:

/**
 * 上传api接口
 */
const Router = require("koa-router");

const router = new Router({
  prefix: "/api/v1/upload" // 路由添加前缀
});

const multer = require("koa-multer");
const path = require("path");

const { Auth } = require("../../../middlewares/auth");

const AUTH_ADMIN = 16;

// 配置
let storage = multer.diskStorage({
  // 文件保存路径, 这里需要自己手动到public下面新建upload文件夹。
  destination: function(req, file, cb) {
    cb(null, "public/upload");
  },
  // 修改文件名称
  filename: function(req, file, cb) {
    let fileFormat = file.originalname.split("."); //以点分割成数组,数组的最后一项就是后缀名
    cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
  }
});
// 加载配置
let upload = multer({
  storage: storage,
  limits: {
    fileSize: (1024 * 1024) / 2 // 限制512KB
  }
});

// 上传文件
router.post("/add", new Auth(AUTH_ADMIN).m, upload.single('file'), async ctx => {
// 返回结果给前端
  ctx.response.status = 200;
  let data = {
    filename: ctx.req.file.filename
  }
  ctx.body = data
});

module.exports = router;

我这里上传需要传递token进行身份认证。如果不需要,将new Auth(AUTH_ADMIN).m,去掉。

2、前端Element-ui使用upload代码:

<template>
  <div class="wrap">
    测试上传
    <div>token:</div>
    <el-input type="text" v-model="token" />
    <el-upload
      class="upload-demo"
      action="http://localhost:3000/api/v1/upload/add"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      multiple
      name="file"
      :headers="headers"
      :limit="3"
      :on-exceed="handleExceed"
      :file-list="fileList"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">
        只能上传jpg/png文件,且不超过500kb
      </div>
    </el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      token: "",
      fileList: [],
    };
  },
  computed: {
    headers() {
      return {
        'Authorization': "Bearer "+ this.token
      }
    },
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件,本次选择了 ${
          files.length
        } 个文件,共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`);
    }
  }
};
</script>

<style lang="scss" scoped>
.wrap {
  width: 1200px;
  margin: 0 auto;
}
</style>

我这里使用了Bearer token的认证方式。这个和koa2服务端token验证机制有关。
token相关设置,在heaers内设置。

name="file" 这个file名称是和后台约定的。

注意:element-ui的上传组件upload,它是一个文件调用一次请求接口的。

附上koa上传七牛云的文章

https://www.jianshu.com/p/7520e0bee777

猜你喜欢

转载自blog.csdn.net/qq_42991509/article/details/106715727