The node framework Egg uploads pictures to Alibaba Cloud oss

Because the project requirements consider that if too many pictures are stored on the server, it will bring pressure to the server, so the pictures are stored on Alibaba Cloud oss, and I searched for them on the Internet, and sorted out the examples on the Internet.

The recent project used the Alibaba Cloud oss ​​server, so record it here.

The overall idea: After the stream uploaded by the front end is received completely, it is directly transmitted to the interface of oss, and there is no need to cache it on the server, which also reduces the pressure on the server. The main module used is  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;

Guess you like

Origin blog.csdn.net/weixin_44248187/article/details/125547024