feat: add aliOSS

This commit is contained in:
yanglbme 2020-09-13 21:24:27 +08:00
parent a17f6368e0
commit d33412b75d
6 changed files with 168 additions and 136 deletions

View File

@ -1,70 +1,102 @@
import fetch from './fetch';
import store from '../store/index';
import OSS from 'ali-oss';
import Buffer from 'buffer-from';
import {
v4 as uuidv4
} from 'uuid';
function fileUpload(content, filename) {
const fileUploadType = store.state.imgHost;
const activeKey = fileUploadType !== 'default' && localStorage.getItem(`${fileUploadType}Config`)
? fileUploadType : 'default';
const defaultConfig = {
username: 'filess',
repo: 'images',
method: 'put',
accessToken: [
'7715d7ca67b5d3837cfdoocsmde8c38421815aa423510af',
'c411415bf95dbe39625doocsmd5047ba9b7a2a6c9642abe',
'2821cd8819fa345c053doocsmdca86ac653f8bc20db1f1b',
'445f0dae46ef1f2a4d6doocsmdc797301e94797b4750a4c',
'cc1d0c1426d0fd0902bdoocsmdd2d7184b14da61b86ec46',
'b67e9d15cb6f910492fdoocsmdac6b44d379c953bb19eff',
'618c4dc2244ccbbc088doocsmd125d17fd31b7d06a50cf3',
'a4b581732e1c1507458doocsmdc5b223b27dae5e2e16a55'
]
}
switch (activeKey) {
function fileUpload(content, filename) {
const imgHost = localStorage.getItem('imgHost');
!imgHost && localStorage.setItem('imgHost', 'default');
switch (imgHost) {
case 'aliOSS':
return aliOSSUploadFile(content, filename);
case 'default':
return githubUploadFile(content, filename);
case 'github':
return githubUploadFile(content, filename);
default:
break;
return githubUploadFile(content, filename);
}
}
/**
* github 图片上传
* @param {*} content
* @param {*} filename
*/
function getDefaultConfig() {
const date = new Date();
const dir = date.getFullYear() + '/' + (date.getMonth() + 1).toString().padStart(2, '0') + '/' + date.getDate().toString().padStart(2, '0');
const token = defaultConfig.accessToken[Math.floor(Math.random() * defaultConfig.accessToken.length)].replace('doocsmd', '');
return {
method: defaultConfig.method,
headers: {
'Authorization': 'token ' + token
},
url: `https://api.github.com/repos/${defaultConfig.username}/${defaultConfig.repo}/contents/${dir}/`
};
}
function getGitHubConfig() {
const date = new Date();
const dir = date.getFullYear() + '/' + (date.getMonth() + 1).toString().padStart(2, '0') + '/' + date.getDate().toString().padStart(2, '0');
const githubConfig = JSON.parse(localStorage.getItem("githubConfig"));
const repoUrl = githubConfig.repo.replace("https://github.com/", "").replace("http://github.com/", "").replace("github.com/", "").split("/");
const username = repoUrl[0];
const repo = repoUrl[1];
return {
method: 'put',
headers: {
'Authorization': 'token ' + githubConfig.accessToken
},
url: `https://api.github.com/repos/${username}/${repo}/contents/${dir}/`
};
}
function githubUploadFile(content, filename) {
const githubResourceUrl = 'raw.githubusercontent.com/filess/images/master/';
const cdnResourceUrl = 'cdn.jsdelivr.net/gh/filess/images/';
const {
method,
headers,
url
} = store.getters['imageApi/config'];
const isDefault = localStorage.getItem('imgHost') !== 'github';
const config = isDefault ? getDefaultConfig() : getGitHubConfig();
const dateFilename = new Date().getTime() + '-' + uuidv4() + '.' + filename.split('.')[1];
const uploadUrl = url + dateFilename;
return fetch({
url: uploadUrl,
method,
headers,
url: config.url + dateFilename,
method: config.method,
headers: config.headers,
data: {
message: 'Upload image by https://doocs.github.io/md',
message: 'Upload by https://doocs.github.io/md',
content: content
}
}).then(res => {
const imageUrl = res.content.download_url.replace(githubResourceUrl, cdnResourceUrl);
return imageUrl;
const githubResourceUrl = 'raw.githubusercontent.com/filess/images/master/';
const cdnResourceUrl = 'cdn.jsdelivr.net/gh/filess/images/';
return isDefault ? res.content.download_url.replace(githubResourceUrl, cdnResourceUrl) : res.content.download_url;
});
}
function aliOSSUploadFile(content, filename) {
debugger;
const config = store.getters['imageApi/config'];
const dateFilename = new Date().getTime() + '-' + uuidv4() + '.' + filename.split('.')[1];
const dir = config.dir + '/' + dateFilename;
const Buffer = require('buffer-from')
const aliOSSConfig = JSON.parse(localStorage.getItem('aliOSSConfig'));
const buffer = Buffer(content, 'base64');
const OSS = require('ali-oss');
try {
const client = new OSS(config);
const dir = aliOSSConfig.path + '/' + dateFilename;
const client = new OSS({
region: aliOSSConfig.region,
bucket: aliOSSConfig.bucket,
accessKeyId: aliOSSConfig.accessKeyId,
accessKeySecret: aliOSSConfig.accessKeySecret
});
return client.put(dir, buffer).then(res => {
console.log('aliOSSUoladFile', res);
return res.url;
})
} catch (e) {

View File

@ -16,7 +16,7 @@ export function uploadImgFile(file) {
fileApi.fileUpload(base64Content, file.name).then(res => {
resolve(res);
}).catch(err => {
reject(err.message)
reject(err);
})
}
});

View File

@ -2,7 +2,7 @@
<el-dialog title="本地上传" class="upload__dialog" :visible="value" @close="$emit('close')">
<el-tabs type="card" :value="'upload'">
<el-tab-pane class="upload-panel" label="选择上传" name="upload">
<el-select v-model="imgHost" @change="changeImgHost" placeholder="请选择" size="small">
<el-select v-model="imgHost" @change="changeimgHost" placeholder="请选择" size="small">
<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
</el-option>
</el-select>
@ -17,7 +17,7 @@
</el-upload>
</el-tab-pane>
<el-tab-pane class="github-panel" label="GitHub 图床" name="github">
<el-form class="setting-form" ref="form" :model="formGitHub" label-position="right" label-width="120px">
<el-form class="setting-form" ref="form" :model="formGitHub" label-position="right" label-width="140px">
<el-form-item label="GitHub 仓库" :required="true">
<el-input v-model="formGitHub.repo" placeholder="如github.com/yanglbme/resource"></el-input>
</el-form-item>
@ -29,7 +29,36 @@
target="_blank">如何获取 GitHub token</el-link>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">保存配置</el-button>
<el-button type="primary" @click="saveGitHubConfiguration">保存配置</el-button>
</el-form-item>
</el-form>
</el-tab-pane>
<el-tab-pane class="github-panel" label="阿里云 OSS" name="aliOSS">
<el-form class="setting-form" ref="form" :model="formAliOSS" label-position="right" label-width="140px">
<el-form-item label="AccessKey ID" :required="true">
<el-input v-model="formAliOSS.accessKeyId" placeholder="如LTAI4GdoocsmdoxUf13ylbaNHk"></el-input>
</el-form-item>
<el-form-item label="AccessKey Secret" :required="true">
<el-input v-model="formAliOSS.accessKeySecret" show-password
placeholder="如cc1d0c142doocs0902bd2d7md4b14da6ylbabc46"></el-input>
</el-form-item>
<el-form-item label="Bucket" :required="true">
<el-input v-model="formAliOSS.bucket"
placeholder="如doocs"></el-input>
</el-form-item>
<el-form-item label="Bucket 所在区域" :required="true">
<el-input v-model="formAliOSS.region"
placeholder="如oss-cn-shenzhen"></el-input>
</el-form-item>
<el-form-item label="存储路径">
<el-input v-model="formAliOSS.path"
placeholder="如img"></el-input>
<el-link type="primary"
href="https://help.aliyun.com/document_detail/31883.html"
target="_blank">如何使用阿里云 OSS</el-link>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="saveAliOSSConfiguration">保存配置</el-button>
</el-form-item>
</el-form>
</el-tab-pane>
@ -55,6 +84,13 @@ export default {
repo: "",
accessToken: "",
},
formAliOSS: {
accessKeyId: "",
accessKeySecret: "",
bucket: "",
region: "",
path: ""
},
options: [{
value: "default",
label: "默认图床",
@ -63,6 +99,10 @@ export default {
value: "github",
label: "GitHub",
},
{
value: "aliOSS",
label: "阿里云"
}
],
imgHost: "default",
uploadingImg: false,
@ -72,16 +112,18 @@ export default {
if (localStorage.getItem("githubConfig")) {
this.formGitHub = JSON.parse(localStorage.getItem("githubConfig"));
}
if (localStorage.getItem("ImgHost")) {
this.imgHost = localStorage.getItem("ImgHost");
if (localStorage.getItem("aliOSSConfig")) {
this.formAliOSS = JSON.parse(localStorage.getItem("aliOSSConfig"));
}
if (localStorage.getItem("imgHost")) {
this.imgHost = localStorage.getItem("imgHost");
}
},
methods: {
changeImgHost() {
console.log("select img host:", this.imgHost);
localStorage.setItem("ImgHost", this.imgHost);
changeimgHost() {
localStorage.setItem("imgHost", this.imgHost);
},
onSubmit() {
saveGitHubConfiguration() {
if (!(this.formGitHub.repo && this.formGitHub.accessToken)) {
const blankElement = this.formGitHub.repo ? "token" : "GitHub 仓库"
this.$message({
@ -92,12 +134,28 @@ export default {
return;
}
localStorage.setItem("githubConfig", JSON.stringify(this.formGitHub));
console.log("submit github params:", this.formGitHub);
this.$message({
message: "保存成功",
type: "success",
});
},
saveAliOSSConfiguration() {
if (!(this.formAliOSS.accessKeyId && this.formAliOSS.accessKeySecret && this.formAliOSS.bucket && this.formAliOSS.region)) {
this.$message({
showClose: true,
message: `阿里云 OSS 参数配置不全`,
type: "error",
});
return;
}
localStorage.setItem("aliOSSConfig", JSON.stringify(this.formAliOSS));
this.$message({
message: "保存成功",
type: "success",
});
},
//
beforeUpload(file) {
if (!this.validateConfig()) {
@ -128,7 +186,16 @@ export default {
} = this.formGitHub;
if (!repo || !accessToken) {
this.$message.error("未配置 GitHub 参数");
this.$message.error("请先配置 GitHub 图床参数");
return false;
}
case 'aliOSS':
const {
accessKeyId, accessKeySecret, bucket, region, path
} = this.formAliOSS;
if (!(accessKeyId && accessKeySecret && bucket && region)) {
this.$message.error("请先配置阿里云 OSS 参数");
return false;
}
}

View File

@ -1,74 +0,0 @@
const state = {
imgHost: localStorage.getItem("ImgHost") || 'default', // 默认github
default: {
username: 'filess',
repo: 'images',
method: 'put',
accessToken: [
'7715d7ca67b5d3837cfdoocsmde8c38421815aa423510af',
'c411415bf95dbe39625doocsmd5047ba9b7a2a6c9642abe',
'2821cd8819fa345c053doocsmdca86ac653f8bc20db1f1b',
'445f0dae46ef1f2a4d6doocsmdc797301e94797b4750a4c',
'cc1d0c1426d0fd0902bdoocsmdd2d7184b14da61b86ec46',
'b67e9d15cb6f910492fdoocsmdac6b44d379c953bb19eff',
'618c4dc2244ccbbc088doocsmd125d17fd31b7d06a50cf3',
'a4b581732e1c1507458doocsmdc5b223b27dae5e2e16a55'
]
},
aliOSS: {
bucket: '<Your BucketName>',
// region以杭州为例oss-cn-hangzhou其他region按实际情况填写。
region: '<Your Region>',
// 阿里云主账号AccessKey拥有所有API的访问权限风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维请登录RAM控制台创建RAM账号。
accessKeyId: '<Your AccessKeyId>',
accessKeySecret: '<Your AccessKeySecret>',
},
qiniuCloud: {}
};
const getters = {
config(state) {
const date = new Date();
const dir = date.getFullYear() + '/' + (date.getMonth() + 1).toString().padStart(2, '0') + '/' + date.getDate().toString().padStart(2, '0');
const activeKey = state.imgHost !== 'default' && localStorage.getItem(`${state.imgHost}Config`) ? state.imgHost : 'default';
switch (activeKey) {
case 'aliOSS':
return {
...state.aliOSS,
dir
};
case 'qiniuCloud':
return {
};
case 'github':
const githubConfig = JSON.parse(localStorage.getItem("githubConfig"));
const repoUrl = githubConfig.repo.replace("https://github.com/", "").replace("http://github.com/", "").replace("github.com/", "").split("/");
const username = repoUrl[0];
const repo = repoUrl[1];
return {
method: 'put',
headers: {
'Authorization': 'token ' + githubConfig.accessToken
},
url: `https://api.github.com/repos/${username}/${repo}/contents/${dir}/`
};
default:
const token = state.default.accessToken[Math.floor(Math.random() * state.default.accessToken.length)].replace('doocsmd', '');
return {
method: state.default.method,
headers: {
'Authorization': 'token ' + token
},
url: `https://api.github.com/repos/${state.default.username}/${state.default.repo}/contents/${dir}/`
};
}
}
};
export default {
namespaced: true,
state,
getters
}

View File

@ -10,8 +10,6 @@ import {
setColor,
formatDoc
} from '../assets/scripts/util'
// module
import imageApi from './imageApi.js';
Vue.use(Vuex)
@ -156,8 +154,5 @@ const mutations = {
export default new Vuex.Store({
state,
mutations,
actions: {},
modules: {
imageApi
}
actions: {}
})

View File

@ -135,6 +135,18 @@ export default {
for (let i = 0, len = e.clipboardData.items.length; i < len; ++i) {
let item = e.clipboardData.items[i]
if (item.kind === 'file') {
//
const imgHost = localStorage.getItem('imgHost') || 'default';
if (imgHost != 'default' && !localStorage.getItem(`${imgHost}Config`)) {
this.$message({
showClose: true,
message: '请先配置好图床参数',
type: 'error'
});
continue;
}
this.isImgLoading = true;
const pasteFile = item.getAsFile()
uploadImgFile(pasteFile).then(res => {