byt-ui
Version:
byt组件库
136 lines (129 loc) • 4 kB
JavaScript
class Minio {
constructor(opts = {}) {
this.minioClient = null;
this.register(opts)
}
register(opts = {}) {
const { accessKey, secretKey, endPoint, port } = opts;
const ssl = window.location.protocol == 'https:';
const minio = require('minio')
this.minioClient = new minio.Client({
endPoint: endPoint || window.location.hostname,
port: port || 19000, // 因endPoint与port无法进行路径拼接,线上发布需要通过特殊端口号19000进行代理转发
useSSL: ssl,
accessKey: accessKey || 'bonyear',
secretKey: secretKey || 'byt12356'
});
}
// 判断储存桶是否存在
minioBucketExists(bucketName) {
return new Promise((reslove) => {
this.minioClient.bucketExists(bucketName).then((flag) => {
reslove(flag)
}).catch(() => {
reslove(false)
});
})
}
// 创建桶
minioMakeBucket(bucketName) {
return new Promise((resolve, reject) => {
this.minioClient.makeBucket(bucketName, 'us-east-1', (err) => {
if (err) return reject(err)
// 设置桶允许访问策略
const policy = JSON.stringify({
Version: '2012-10-17',
Statement: [{
Sid: '',
Effect: 'Allow',
Principal: '*',
Action: [
's3:GetBucketLocation',
's3:ListBucket',
's3:GetObject',
's3:PutObject'
],
Resource: [
`arn:aws:s3:::${bucketName}/*`
]
}]
});
this.minioClient.setBucketPolicy(bucketName, policy, (error) => {
if (error) {
// console.error('桶:创建失败', error);
reject(error)
} else {
// console.log('桶:创建成功');
resolve()
}
});
})
})
}
putObject(file, bucketName, fileName) {
return new Promise((resolve, reject) => {
const metaData = {
'Content-Type': file.type
}
const reader = new FileReader();
const stream = require('stream')
reader.readAsArrayBuffer(file);
// 分段处理二进制流
reader.onloadend = (e) => {
// 读取完成触发,无论成功或失败
const blobData = e.target.result;
const bufferStream = new stream.PassThrough();
bufferStream.end(Buffer.from(blobData));
this.minioClient.putObject(bucketName, fileName, bufferStream, file.size, metaData, (err, etag) => {
if (err) {
return reject(err);
}
return resolve(etag);
})
};
})
}
async uploadToMinio({
file,
bucketName,
fileName = ''
}) {
if (!bucketName) return Promise.reject(new Error('请传入桶名'));
const flag = await this.minioBucketExists(bucketName)
if (!flag) {
await this.minioMakeBucket(bucketName)
}
return new Promise((resolve, reject) => {
this.putObject(file, bucketName, fileName).then(res => {
resolve(res)
}).catch((err) => {
reject(err)
})
})
}
upload(file, bucketName = 'public', unHodeName = true) {
// file:文件
// bucketName:桶名
// unHodeName:是否保留原文件名,默认不保留
// 上传图片至minio
const { name } = file;
const suffix = name.match(/\.[a-zA-Z\d]+$/i);
const fileName = unHodeName ? `${new Date().getTime()}${suffix[0]}` : name
return new Promise((resolve, reject) => {
this.uploadToMinio({
file,
bucketName,
fileName
}).then(() => {
resolve(`/minio/${bucketName}/${fileName}`)
}).catch(err => {
reject(err)
})
})
}
}
export default {
install(Vue, options = {}) {
Vue.prototype.$minio = new Minio(Object.assign({}, options))
}
}