diff --git a/README.md b/README.md index 2f229cb..01ff1e1 100644 --- a/README.md +++ b/README.md @@ -46,10 +46,10 @@ exports.cos = { // {app_root}/config/config.default.js exports.cos = { client: { - secretId: '', - secretKey: '', - bucket: '', - region: '', + SecretId: '', + SecretKey: '', + Bucket: '', + Region: '', } }; ``` @@ -62,6 +62,88 @@ exports.cos = { }; ``` +## Usage + +You can aquire tencent cloud cos instance on `app` or `ctx`. +// upload a file in controller + +- File Mode:The file is temporarily stored as cache in your server during the process; + +```js +const path = require('path'); +const Controller = require('egg').Controller; + +module.exports = class extends Controller { + async upload() { + const ctx = this.ctx; + // please enable `file` mode of `egg-multipart`. + const file = ctx.request.files[0]; + const name = 'egg-cos/' + path.basename(file.filename); + let result; + try { + result = await ctx.cos.put(name, file.filepath); + } finally { + // need to remove the tmp files + await ctx.cleanupRequestFiles(); + } + + if (result) { + ctx.logger.info('cos response:\n', result); + ctx.body = { + url: `https://${result.Location}` + }; + } else { + ctx.body = 'please select a file to upload!'; + } + } +}; +``` +- upload by Stream:The file is transfered to cloud server directly, not go through your server; + +```js +const Controller = require('egg').Controller; +const sendToWormhole = require('stream-wormhole'); +async upload() { + const ctx = this.ctx; + const parts = ctx.multipart(); + let part,results=[]; + while ((part = await parts()) != null) { + if (part.length) { + // This is content of part stream + console.log('field: ' + part[0]); + console.log('value: ' + part[1]); + console.log('valueTruncated: ' + part[2]); + console.log('fieldnameTruncated: ' + part[3]); + } else { + if (!part.filename) { + return; + } + console.log('field: ' + part.fieldname); + console.log('filename: ' + part.filename); + console.log('encoding: ' + part.encoding); + console.log('mime: ' + part.mime); + console.log("part",part.stream,typeof part); + // file processing, uploading the file to Tencent Cloud Server + let result; + let path=await ctx.helper.MD5encode(String(Date.now())); + let typeArray=part.mime.split('/'); + let type=typeArray[typeArray.length-1]; + let name='ysxbdms/projects/'+path+`.${type}`;//the upload links + try { + result = await ctx.cos.putStream(name,part); + } catch (err) { + await sendToWormhole(part); + throw err; + } + console.log(result); + results.push(result); + } + } + console.log('and we are done parsing the form!'); + ctx.body=results; +}; +``` + ## Questions & Suggestions Please open an issue [here](https://github.com/romoo/egg-cos/issues). diff --git a/app/extend/context.js b/app/extend/context.js new file mode 100644 index 0000000..ac042bc --- /dev/null +++ b/app/extend/context.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = { + get cos() { + return this.app.cos; + }, +}; diff --git a/lib/cos.js b/lib/cos.js index 197e32f..2821a7f 100644 --- a/lib/cos.js +++ b/lib/cos.js @@ -1,15 +1,62 @@ 'use strict'; const assert = require('assert'); -const COS = require('cos-nodejs-sdk-v5'); +const COS_NODEJS_SDK = require('cos-nodejs-sdk-v5'); + +class COS extends COS_NODEJS_SDK { + constructor(options) { + super(options); + this.Bucket = options.Bucket || ''; + this.Region = options.Region || ''; + } + + /** + * 上传本地文件到COS文件储存桶 + * @param {String} Key 设定上传到cos的路径 + * @param {String} FilePath 本地需要上传的文件 + * @param {Object} options 设定Bucket存储桶和Region区域的选项 + * @return {Promise<Object>} Promise包裹的data + */ + put(Key, FilePath, options = {}) { + const Bucket = options.Bucket || this.Bucket; + const Region = options.Region || this.Region; + return new Promise((s, j) => { + this.sliceUploadFile({ Bucket, Region, Key, FilePath }, (err, data) => { + err ? j(JSON.stringify(err)) : s(data); + }); + }); + } + + /** + * stream 模式上传文件,不用在服务器缓存 + * @param {String} Key 设定上传到cos的路径 + * @param {Object} Body 本地需要上传的文件流 + * @param {Object} options 设定Bucket存储桶和Region区域的选项 + * @return {Promise<Object>} Promise包裹的data + */ + putStream(Key, Body, options = {}) { + const Bucket = options.Bucket || this.Bucket; + const Region = options.Region || this.Region; + return new Promise((s, j) => { + this.putObject({ Bucket, Region, Key, Body }, (err, data) => { + err ? j(JSON.stringify(err)) : s(data); + }); + }); + } +} const createOneClient = (config, app) => { - assert(config.secretId && config.secretKey, '[egg-cos] secretId secretKey is required on config'); - app.coreLogger.info('[egg-cos] init %s', config.secretId); + assert( + config.SecretId && config.SecretKey, + '[egg-cos] `SecretId` `SecretKey` is required on config' + ); + app.coreLogger.info('[egg-cos] init %s', config.SecretId); return new COS({ - SecretId: config.secretId, - SecretKey: config.secretKey, + SecretId: config.SecretId, + SecretKey: config.SecretKey, + Bucket: config.Bucket, + Region: config.Region, }); }; diff --git a/package.json b/package.json index 4f29415..a1862e4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "egg-cos", - "version": "1.0.3", + "version": "2.0.0", "description": "tencent cloud cos plugin for egg", "eggPlugin": { "name": "cos"