From d33412b75dd3d88b21c51861ad081f98c7279d58 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Sun, 13 Sep 2020 21:24:27 +0800 Subject: [PATCH] feat: add aliOSS --- src/api/file.js | 116 +++++++++++------- src/assets/scripts/uploadImageFile.js | 2 +- .../CodemirrorEditor/uploadImgDialog.vue | 93 ++++++++++++-- src/store/imageApi.js | 74 ----------- src/store/index.js | 7 +- src/view/CodemirrorEditor.vue | 12 ++ 6 files changed, 168 insertions(+), 136 deletions(-) delete mode 100644 src/store/imageApi.js diff --git a/src/api/file.js b/src/api/file.js index 067f451..7a3d081 100644 --- a/src/api/file.js +++ b/src/api/file.js @@ -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 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 dateFilename = new Date().getTime() + '-' + uuidv4() + '.' + filename.split('.')[1]; - const uploadUrl = url + dateFilename; +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 isDefault = localStorage.getItem('imgHost') !== 'github'; + const config = isDefault ? getDefaultConfig() : getGitHubConfig(); + const dateFilename = new Date().getTime() + '-' + uuidv4() + '.' + filename.split('.')[1]; + 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; + }).then(res => { + 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); - - return client.put(dir, buffer).then(res=> { - console.log('aliOSSUoladFile', res); + 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 => { return res.url; }) } catch (e) { diff --git a/src/assets/scripts/uploadImageFile.js b/src/assets/scripts/uploadImageFile.js index 2b50c8b..ee0b185 100644 --- a/src/assets/scripts/uploadImageFile.js +++ b/src/assets/scripts/uploadImageFile.js @@ -16,7 +16,7 @@ export function uploadImgFile(file) { fileApi.fileUpload(base64Content, file.name).then(res => { resolve(res); }).catch(err => { - reject(err.message) + reject(err); }) } }); diff --git a/src/components/CodemirrorEditor/uploadImgDialog.vue b/src/components/CodemirrorEditor/uploadImgDialog.vue index db691cd..63f7e8e 100644 --- a/src/components/CodemirrorEditor/uploadImgDialog.vue +++ b/src/components/CodemirrorEditor/uploadImgDialog.vue @@ -2,7 +2,7 @@ - + @@ -17,7 +17,7 @@ - + @@ -29,7 +29,36 @@ target="_blank">如何获取 GitHub token? - 保存配置 + 保存配置 + + + + + + + + + + + + + + + + + + + + 如何使用阿里云 OSS? + + + 保存配置 @@ -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()) { @@ -106,11 +164,11 @@ export default { this.uploadingImg = true; uploadImgFile(file) - .then(res=> { + .then(res => { this.$emit("uploaded", res); this.uploadingImg = false; }) - .catch(err=> { + .catch(err => { this.uploadingImg = false; this.$message({ showClose: true, @@ -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; } } diff --git a/src/store/imageApi.js b/src/store/imageApi.js deleted file mode 100644 index 78afe66..0000000 --- a/src/store/imageApi.js +++ /dev/null @@ -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: '', - // region以杭州为例(oss-cn-hangzhou),其他region按实际情况填写。 - region: '', - // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。 - accessKeyId: '', - 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 -} \ No newline at end of file diff --git a/src/store/index.js b/src/store/index.js index cf12b26..30ffadf 100644 --- a/src/store/index.js +++ b/src/store/index.js @@ -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: {} }) diff --git a/src/view/CodemirrorEditor.vue b/src/view/CodemirrorEditor.vue index 8740ec4..b9d449c 100644 --- a/src/view/CodemirrorEditor.vue +++ b/src/view/CodemirrorEditor.vue @@ -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 => {