npm:egg-oss安装与使用

本文涉及的产品
对象存储 OSS,20GB 3个月
对象存储 OSS,恶意文件检测 1000次 1年
对象存储 OSS,内容安全 1000次 1年
简介: npm:egg-oss安装与使用

官网:https://www.npmjs.com/package/egg-oss


安装


npm i egg-oss --save


配置


在 config/plugin.js 中写入配置


exports.oss = {
  enable: true,
  package: 'egg-oss',
};
// config/config.default.js
config.multipart = {
    mode: 'file'
};
// oss存储
config.oss = {  // 这里需要的东西去自己的服务器里看,我用的阿里云
    client: {
        accessKeyId: 'your access key',
        accessKeySecret: 'your access secret',
        bucket: 'your bucket name',
        endpoint: 'oss-cn-hongkong.aliyun.com',
        timeout: '60s',
    },
}


使用


在 app/controller/common.js 中 编写upload路由的方法


'use strict';
const Controller = require('egg').Controller;
const fs = require('mz/fs');
const path = require('path')
class CommonController extends Controller {
    // 上传
    async upload() {
        const ctx = this.ctx;
        if (!ctx.request.files) {
            return ctx.apiFail('请先选择上传文件');
        }
        const file = ctx.request.files[0];
        // const name = 'egg-oss-demo/' + path.basename(file.filename);
        const name = 'egg-oss-demo/' + ctx.genID(10) + path.extname(file.filename);
        let result;
        try {
            result = await ctx.oss.put(name, file.filepath);
        } catch (err) {
            console.log(err);
        } finally {
            await fs.unlink(file.filepath);
        }
        if (result) {
            return ctx.apiSuccess(result.url);
        }
        ctx.apiFail('上传失败');
    }
}
module.exports = CommonController;


在 app/extend/context.js 填写生成唯一ID的扩展


// 生成唯一id
genID(length) {
    return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
}
相关实践学习
借助OSS搭建在线教育视频课程分享网站
本教程介绍如何基于云服务器ECS和对象存储OSS,搭建一个在线教育视频课程分享网站。
相关文章
|
3月前
|
缓存 资源调度
解决安装依赖时报错:npm ERR! code ERESOLVE
解决安装依赖时报错:npm ERR! code ERESOLVE
868 0
解决安装依赖时报错:npm ERR! code ERESOLVE
|
4月前
|
JavaScript 前端开发 开发者
windows安装npm教程
windows安装npm教程
|
4月前
|
JavaScript 安全 Windows
NPM包的安装、更新、卸载
NPM包的安装、更新、卸载
|
5月前
|
缓存
npm修改全局包安装路径
npm修改全局包安装路径
|
4月前
npm 切换镜像后,npm i 安装依然卡,需要好久才完成
npm 切换镜像后,npm i 安装依然卡,需要好久才完成
145 0
|
4天前
|
缓存 资源调度
npm install安装时一直idealTree:npm: sill idealTree buildDeps解决方案(亲测有效)
npm install安装时一直idealTree:npm: sill idealTree buildDeps解决方案(亲测有效)
17 2
|
5月前
|
Linux iOS开发 MacOS
npm将软件包安装到哪里
npm将软件包安装到哪里
|
5月前
|
缓存
【已解决】npm安装依赖报错: npm ERR! cb() never called! npm ERR! This is an error with npm itself.
【已解决】npm安装依赖报错: npm ERR! cb() never called! npm ERR! This is an error with npm itself.
335 0
|
1月前
npm从非官方源安装
npm从非官方源安装
|
2月前
|
JavaScript Ubuntu Linux
Linux ubuntu安装nodejs/npm
Linux ubuntu安装nodejs/npm

推荐镜像

更多