上传图片到腾讯云COS
// 在 app/controller/user.js
'use strict';
var COS = require('cos-nodejs-sdk-v5');
const path = require('path');
var cos = new COS({
SecretId: 'XXXXXXXXXXXX',
SecretKey: 'XXXXXXXXx',//私钥
});
const Controller = require('egg').Controller;
class Uploadcontroller extends Controller {
async upload(){
const { ctx,app} = this;
const stream = await this.ctx.getFileStream();
const filename = Date.now() + path.extname(stream.filename).toLocaleLowerCase();
cos.putObject({
Bucket: 'XXXXXXXXX', /* Bucket,名称 必须 */
Region: 'ap-beijing', /* 所属地域 必须 */
Key: filename, /* 必须 */
Body:stream, // 上传文件对象
onProgress: function(progressData) {
console.log(JSON.stringify(progressData));//返回信息,包括路径
}
}, function(err, data) {
console.log(err || data);
});
}
}
module.exports = Uploadcontroller;
上传到本地服务器
// 在 app/controller/user.js
'use strict';
import path from 'path'
const fs = require('fs');
const path = require('path');
const Controller = require('egg').Controller;
class Uploadcontroller extends Controller {
async upload(){
const { ctx,app} = this;
const stream = await this.ctx.getFileStream();
const filename = Date.now() + path.extname(stream.filename).toLocaleLowerCase();
const target = path.join(this.config.baseDir, 'app/public', filename);
const writeStream = fs.createWriteStream(target);//上传到本地存储桶
const filePath = writeStream.path //拿到路径
}
}
module.exports = Uploadcontroller;