egg上传图片到阿里云oss

因为项目需求考虑到图片储存在服务器上过多的话会对服务器带来压力,所以讲图片存在阿里云oss上,网上找了下,综合网上的示例整理了下,有需要的大哥可以拿去用!我这用到的是nodejs的框架Eggjs

整体思路:将前端上传的流接受完整后直接传给oss的接口,不必在服务器再缓存一下,这样也减轻了服务器的压力,主要用到的模块是 ali-oss

//controller
'use strict';
const path = require('path');
const oss = require('ali-oss');
const BaseController = require("./base");

class GoodsController extends BaseController {
    async doAdd() {
        const { ctx, service, app } = this;
        let parts = ctx.multipart({ autoFields: true });
        let stream;

        //可以配置在config
        const client = new oss({
            accessKeyId: 'xxx',
            accessKeySecret: 'xxx',
            bucket: 'xxx',
            region: 'oss-cn-shenzhen',//替换成自己的地区,我这是深圳
        });
        
        while ((stream = await parts()) != null) {
            if (!stream.filename) {
                break;
            }
            let name = `test${path.extname(stream.filename)}`;
            client.putStream(name, stream).then(function (r1) {
                console.log('put success: %j',r1);
                return client.get('object');
            }).then(function (r2) {
                console.log('get success: %j');
            }).catch(function (err) {
                console.error('error: %j');
            });
            
        }
        ctx.body = "ok"
    }
}

module.exports = GoodsController;

你可能感兴趣的:(egg上传图片到阿里云oss)