最近公司里需要用到一个图片上传,要求是根据接口来判断是阿里云上传还是minio上传,如果判断是阿里云上传,就走阿里云上传的步骤,如果是minio上传就走minio上传的步骤,于是对这个需求进行了封装。
首先总的入口文件是uploader.js,代码如下
import data from '@/store/modules/data';
import Sts from './sts'
import UploaderAlioss from './uploader.alioss';
import UploaderMinio from './uploader.minio';
const Uploader = {};
const createFileKey = (type, name) => {
let filename = 'upload/';
let filetype = type.substring(0, type.indexOf('/'));
switch (filetype) {
case 'image':
filename += 'images/';
break;
case 'video':
filename += 'videos/';
break;
default:
filename += 'files/';
break;
}
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
if (month < 10) {
month = "0" + month;
}
if (day < 10) {
day = "0" + day;
}
filename += year.toString() + month.toString() + day.toString() + '/' + date.getTime().toString() + randomNum(5) + name.substring(name.lastIndexOf('.'));
return filename
}
const randomNum = (n) => {
var rnd = "";
for (var i = 0; i < n; i++)
rnd += Math.floor(Math.random() * 10);
return rnd;
}
const upladImage = async (fileObject, progressFun) => {
let key = createFileKey(fileObject.type, fileObject.name);
let info = await Sts.getStsInfo();
if (info.type == 'ALI_YUN') {
UploaderAlioss.init(info.stsInfo);
let response = await UploaderAlioss.upladImage(fileObject, key, progressFun);
if(response.res.status==200&&response.res.requestUrls.length>0){
return response.res.requestUrls[0].lastIndexOf('?')>0?response.res.requestUrls[0].substring(0,response.res.requestUrls[0].lastIndexOf('?')):response.res.requestUrls[0];
}
}
if (info.type == 'MINIO') {
UploaderMinio.init(info.stsInfo);
let response = await UploaderMinio.upladFile(info.stsInfo,fileObject,key);
return response
}
return null
}
Uploader.upladImage = upladImage;
export default Uploader;
上面的文件做了判断,如果是阿里云就走阿里云的上传,如果是minio就走minio的上传,所以分别对这两个上传进行了封装,下面是封装的代码。
阿里云封装:
const OSS = require('ali-oss');
let client
const UploaderAlioss = {};
const init = (stsInfo) => {
client = new OSS({
// yourRegion填写Bucket所在地域。以华东1(杭州)为例,Region填写为oss-cn-hangzhou。
region: 'oss-cn-qingdao',
// 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
accessKeyId: stsInfo.accessKeyId,
accessKeySecret: stsInfo.accessKeySecret,
// 从STS服务获取的安全令牌(SecurityToken)。
stsToken: stsInfo.securityToken,
// 填写Bucket名称。
bucket: 'everyedu'
});
}
const upladImage = async (fileObject, key, progressFun) => {
return await client.multipartUpload(key, fileObject, {
progress: function (p, checkpoint) {
if(progressFun!=undefined){
progressFun(p);
}
},
})
}
UploaderAlioss.init = init;
UploaderAlioss.upladImage = upladImage;
export default UploaderAlioss
minio的封装:
const Minio = require('minio');
const stream = require('stream')
let client
const UploaderMinio = {};
const init = (stsInfo) => {
client = new Minio.Client({
endPoint: getUrl(stsInfo.url), // 地址
// port: xx, // 端口号,若地址为类似test.minio.com,就不必写端口号
useSSL: getSsl(stsInfo.url), // 是否使用ssl
accessKey:stsInfo.accessKey, // 登录的accessKey
secretKey: stsInfo.secretKey, // secretKey
sessionToken:stsInfo.sessionToken,
});
}
function getUrl(url){
let index = url.indexOf("/");
let result = url.substr(index + 2,url.length);
return result
}
function getSsl(url){
let index=url.indexOf("https")
if(index==-1){
return false
}else{
return true
}
}
const upladImage = async (info,fileObject, key, progressFun) => {
}
const upladFile = async (info,fileObject, key) => {
return new Promise((resolve, reject) => {
let metadata = {
"content-type": fileObject.type,
"content-length": fileObject.size
}
let reader = new FileReader();
reader.readAsDataURL(fileObject);
reader.onloadend = function (e) {
const dataurl = e.target.result;
const blob = toBlob(dataurl);
let reader2 = new FileReader()
reader2.readAsArrayBuffer(blob)
reader2.onload = function (ex) {
let bufferStream = new stream.PassThrough()
bufferStream.end(new Buffer(ex.target.result))
client.putObject(info.bucket, key, bufferStream, fileObject.size, metadata, function(err, etag) {
if (err == null) {
let res = {
path: `${info.url}/${info.bucket}/${key}`,
status:200
};
resolve(res)
}else{
let res={
path:'',
status: 400,
}
resolve(res)
}
})
}
}
})
}
function toBlob (base64Data) {
let byteString = base64Data
if (base64Data.split(',')[0].indexOf('base64') >= 0) {
byteString = atob(base64Data.split(',')[1]) // base64 解码
} else {
byteString = unescape(base64Data.split(',')[1])
}
let mimeString = base64Data.split(';')[0].split(":")[1] // mime类型
let uintArr = new Uint8Array(byteString.length) // 创建视图
for (let i = 0; i < byteString.length; i++) {
uintArr[i] = byteString.charCodeAt(i)
}
const blob = new Blob([uintArr], {
type: mimeString
})
return blob
}
UploaderMinio.init = init;
UploaderMinio.upladImage = upladImage;
UploaderMinio.upladFile = upladFile;
export default UploaderMinio
希望这篇文章能帮到你们,有什么问题可以留言
|