egg-obs

0.0.3 • Public • Published

egg-obs

NPM version build status Test coverage David deps Known Vulnerabilities npm download

OBS plugin for egg

Install

$ npm i egg-obs --save

Configuration

// config/plugin.js
exports.obs = {
  enable: true,
  package: 'egg-obs',
};
// config/config.default.js
exports.obs = {
  access_key_id: '',
  secret_access_key: '',
  server: '',
  bucket: ''
};

see config/config.default.js for more detail.

Usage

  • putObject({ key, imageProcess })
  • getObject({ key, body })
  • delObject({ key })
  • setBucket(name)

You can require obs instance on app or ctx.

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

module.exports = class extends Controller {
  // upload file
  async upload() {
    const { ctx } = this
    const stream = await ctx.getFileStream()
    const filename = Math.floor(Math.random() * 10000) + path.extname(stream.filename)
    
    try {
      await ctx.obs.putObject({
        key: filename,
        body: stream
      });
      ctx.body = `/obs-image/${filename}`
    } catch (error) {
      ctx.body = error;
      ctx.logger.error(new Error(error));
    }
  }

  // get file
  async getImage() {
    const { ctx } = this
    const objectname = ctx.params.objectname;
    try {
      const result = await ctx.obs.getObject({ key: objectname })
      if (result.CommonMsg.Status < 300 && result.InterfaceResult) {
        // 读取对象内容
        const { ContentLength, Date, ETag, ContentType, Content } = result.InterfaceResult
        ctx.status = 200
        ctx.type = ContentType
        ctx.etag = ETag
        ctx.length = ContentLength
        ctx.set('Date', Date)
        ctx.body = Content
      } else {
        ctx.body = result.CommonMsg.Message
      }
    } catch (error) {
      ctx.body = error
      ctx.logger.error(new Error(error));
    }
  }
};

Questions & Suggestions

If upload blob file, ctx.getFileStream() will prompt [Invalid filename: blob] error.

Use config.multipart = { fileExtensions: [''] } to fix it.

Please open an issue here.

License

MIT

Package Sidebar

Install

npm i egg-obs

Weekly Downloads

13

Version

0.0.3

License

MIT

Unpacked Size

9.9 kB

Total Files

8

Last publish

Collaborators

  • chenjunru