美文网首页
egg上传图片到腾讯云COS和上传图片到本地服务器

egg上传图片到腾讯云COS和上传图片到本地服务器

作者: 凉生可可 | 来源:发表于2020-04-28 15:40 被阅读0次

上传图片到腾讯云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;

相关文章

网友评论

      本文标题:egg上传图片到腾讯云COS和上传图片到本地服务器

      本文链接:https://www.haomeiwen.com/subject/sbzvwhtx.html