egg-oss 上传图片

7 篇文章 0 订阅

一、安装 egg-oss

npm install egg-oss --save

二、配置 oss

1、开启 oss 插件

// config/plugin.js
exports.oss = {
  enable: true,
  package: 'egg-oss',
};

2、填写 oss bucket 信息

// config/config.default.js
config.oss = {
  client: {
    bucket: 'your bucket name',
    region: 'your bucket region(e.g. oss-cn-shenzhen)',
    accessKeyId: 'your access key',
    accessKeySecret: 'your access secret',
    secure: true,
  },
};

3、因 Egg 默认开启 CSRF 防护,若目前不想配置 CSRF,可先关闭

// config/config.default.js
config.security = {
  csrf: {
    enable: false,
  },
};

三、使用演示

1、编辑 Controller

// app/controller/upload.js
'use strict';

const path = require('path');
const Controller = require('egg').Controller;

class UploadController extends Controller {
  /**
   * 上传头像
   */
  async uploadAvatar() {
    const { ctx } = this;

    let filePath;
    const stream = await ctx.getFileStream();

    if (stream.fields.filePath) {
      filePath = stream.fields.filePath + '/' + path.basename(stream.filename);
    } else {
      filePath = path.basename(stream.filename);
    }

    const result = await ctx.oss.put(filePath, stream);

    ctx.body = {
      code: 0,
      message: '上传成功',
      data: { url: result.url },
    };
  }
}

module.exports = UploadController;

2、配置 Router

// app/router.js
'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.post('/api/v1/uploadAvatar', controller.upload.uploadAvatar);
};

四、通过 Vue + Element UI 演示效果

1、配置 API 代理转发到 Egg 服务

// vue.config.js
module.exports = {
  devServer: {
    proxy: {
      '/api/v1': {
        target: 'http://localhost:7001' // Egg 服务地址
      }
    }
  }
}

2、使用 Element UI 中 Upload 组件演示 Demo

<template>
  <el-upload
    class="avatar-uploader"
    action="api/v1/uploadAvatar"
    :data="{ filePath: 'egg-oss-demo' }"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
export default {
  name: 'Home',
  data () {
    return {
      imageUrl: ''
    }
  },
  methods: {
    handleAvatarSuccess (result) {
      this.imageUrl = result.data.url
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('Avatar picture must be JPG format!')
      }
      if (!isLt2M) {
        this.$message.error('Avatar picture size can not exceed 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  line-height: 178px !important;
  color: #8c939d;
  text-align: center;
}

.avatar {
  display: block;
  width: 178px;
  height: 178px;
}
</style>

3、动画演示

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值