1.安装插件
npm i egg-oss --save
2.开启oss插件
配置路径:{app_root}/config/plugin.js
oss : { enable: true, package: 'egg-oss', }
3.配置阿里云oss参数
配置路径:{app_root}/config/config.plugin.js
config.multipart = { mode: 'file' }; config.oss = { // 这里需要的东西去自己的服务器里看,我用的阿里云 client: { accessKeyId: 'xxxx', accessKeySecret: 'xxxxx', bucket: 'xxxxxx', endpoint: 'xxxxxx', timeout: '60s', }, }
4.控制器
'use strict'; const Controller = require('egg').Controller; const fs = require('mz/fs'); const path = require('path') class AliyunossController extends Controller { // 上传 async upload() { const ctx = this.ctx; const file = ctx.request.files[0]; if (!file) { return ctx.apiFail('请先选择上传文件'); } const name = 'movie/' + 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 = AliyunossController;
5.封装的api扩展(非必须)
路径:app/extend/context.js
module.exports = { // 成功提示 apiSuccess(data = '', msg = 'ok', code = 200) { this.body = { msg, data }; this.status = code; }, // 失败提示 apiFail(data = '', msg = 'fail', code = 400) { this.body = { msg, data }; this.status = code; }, // 生成唯一id genID(length) { return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36); } };
6.路由
配置地址:app/router.js
router.post('/api/aliyunoss/upload', controller.aliyunoss.upload);
7.测试文件
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>上传图片至阿里云oss测试</title> </head> <body> <form method="POST" action="http://127.0.0.1:7001/api/aliyunoss/upload" enctype="multipart/form-data"> 文件: <input name="file" type="file" /> <button type="submit">上传</button> </form> </body> </html>
标签:上传,const,config,oss,ctx,阿里,file,Egg From: https://www.cnblogs.com/jn-zc/p/17011533.html