一、安装 egg-oss
npm install egg-oss --save
二、配置 oss
1、开启 oss 插件
// config/plugin.js
exports.oss = {
enable: true,
package: 'egg-oss',
};
2、填写 oss bucket 信息
// config/config.default.js
config.oss = {
client: {
bucket: 'your bucket name',
region: 'your bucket region(e.g. oss-cn-shenzhen)',
accessKeyId: 'your access key',
accessKeySecret: 'your access secret',
secure: true,
},
};
3、因 Egg 默认开启 CSRF 防护,若目前不想配置 CSRF,可先关闭
// config/config.default.js
config.security = {
csrf: {
enable: false,
},
};
三、使用演示
1、编辑 Controller
// app/controller/upload.js
'use strict';
const path = require('path');
const Controller = require('egg').Controller;
class UploadController extends Controller {
/**
* 上传头像
*/
async uploadAvatar() {
const {
ctx } = this;
let filePath;
const stream = await ctx.getFileStream();
if (stream.fields.filePath) {
filePath = stream.fields.filePath + '/' + path.basename(stream.filename);
} else {
filePath = path.basename(stream.filename);
}
const result = await ctx.oss.put(filePath, stream);
ctx.body = {
code: 0,
message: '上传成功',
data: {
url: result.url },
};
}
}
module.exports = UploadController;
2、配置 Router
// app/router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const {
router, controller } = app;
router.post('/api/v1/uploadAvatar', controller.upload.uploadAvatar);
};
四、通过 Vue + Element UI 演示效果
1、配置 API 代理转发到 Egg 服务
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/api/v1': {
target: 'http://localhost:7001' // Egg 服务地址
}
}
}
}
2、使用 Element UI 中 Upload 组件演示 Demo
<template>
<el-upload
class="avatar-uploader"
action="api/v1/uploadAvatar"
:data="{ filePath: 'egg-oss-demo' }"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon" />
</el-upload>
</template>
<script>
export default {
name: 'Home',
data () {
return {
imageUrl: ''
}
},
methods: {
handleAvatarSuccess (result) {
this.imageUrl = result.data.url
},
beforeAvatarUpload (file) {
const isJPG = file.type === 'image/jpeg'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
this.$message.error('Avatar picture must be JPG format!')
}
if (!isLt2M) {
this.$message.error('Avatar picture size can not exceed 2MB!')
}
return isJPG && isLt2M
}
}
}
</script>
<style>
.avatar-uploader .el-upload {
position: relative;
overflow: hidden;
cursor: pointer;
border: 1px dashed #d9d9d9;
border-radius: 6px;
}
.avatar-uploader .el-upload:hover {
border-color: #409eff;
}
.avatar-uploader-icon {
width: 178px;
height: 178px;
font-size: 28px;
line-height: 178px !important;
color: #8c939d;
text-align: center;
}
.avatar {
display: block;
width: 178px;
height: 178px;
}
</style>
3、动画演示