Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplified the using of two uploading ways #1

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 86 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ exports.cos = {
// {app_root}/config/config.default.js
exports.cos = {
client: {
secretId: '',
secretKey: '',
bucket: '',
region: '',
SecretId: '',
SecretKey: '',
Bucket: '',
Region: '',
}
};
```
Expand All @@ -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).
Expand Down
7 changes: 7 additions & 0 deletions app/extend/context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use strict';

module.exports = {
get cos() {
return this.app.cos;
},
};
57 changes: 52 additions & 5 deletions lib/cos.js
Original file line number Diff line number Diff line change
@@ -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,
});
};

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down