Merge pull request #26 from doocs/feat_custom_img_host

Feat custom img host
This commit is contained in:
Yang Libin 2020-08-31 11:48:43 +08:00 committed by GitHub
commit 651cc3d869
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 218 additions and 59 deletions

View File

@ -19,10 +19,28 @@ const fileUploadConfig = {
function fileUpload(content, filename) { function fileUpload(content, filename) {
const date = new Date(); const date = new Date();
const dir = date.getFullYear() + '/' + (date.getMonth() + 1).toString().padStart(2, '0') + '/' + date.getDate().toString().padStart(2, '0'); const dir = date.getFullYear() + '/' + (date.getMonth() + 1).toString().padStart(2, '0') + '/' + date.getDate().toString().padStart(2, '0');
const uuid = uuidv4(); const uuid = uuidv4();
const token = fileUploadConfig.accessToken[Math.floor(Math.random() * fileUploadConfig.accessToken.length)].replace('doocsmd', '');
const dateFilename = new Date().getTime() + '-' + uuid + '.' + filename.split('.')[1]; const dateFilename = new Date().getTime() + '-' + uuid + '.' + filename.split('.')[1];
const url = `https://api.github.com/repos/${fileUploadConfig.username}/${fileUploadConfig.repo}/contents/${dir}/${dateFilename}`; const imgHost = localStorage.getItem("ImgHost") || 'default'
let token = ''
let username = ''
let repo = ''
if (imgHost === 'default') {
token = fileUploadConfig.accessToken[Math.floor(Math.random() * fileUploadConfig.accessToken.length)].replace('doocsmd', '');
username = fileUploadConfig.username
repo = fileUploadConfig.repo
}
if (imgHost === 'github' && localStorage.getItem("GitHubConfig")) {
const githubConfg = JSON.parse(localStorage.getItem("GitHubConfig"));
token = githubConfg.accessToken
username = githubConfg.username
repo = githubConfg.repo
}
const url = `https://api.github.com/repos/${username}/${repo}/contents/${dir}/${dateFilename}`;
return fetch({ return fetch({
url, url,

View File

@ -8,8 +8,8 @@
<img src="https://gitee.com/yanglbme/resource/raw/master/doocs-md/qrcode.png" style="width: 40%; display: block; margin: 20px auto 10px;"> <img src="https://gitee.com/yanglbme/resource/raw/master/doocs-md/qrcode.png" style="width: 40%; display: block; margin: 20px auto 10px;">
</div> </div>
<span slot="footer" class="dialog-footer"> <span slot="footer" class="dialog-footer">
<el-button type="success" @click="onRedirect('https://github.com/doocs/md')" plain>GitHub 仓库</el-button> <el-button type="primary" @click="onRedirect('https://github.com/doocs/md')" plain>GitHub 仓库</el-button>
<el-button type="success" @click="onRedirect('https://gitee.com/doocs/md')" plain>Gitee 仓库</el-button> <el-button type="primary" @click="onRedirect('https://gitee.com/doocs/md')" plain>Gitee 仓库</el-button>
</span> </span>
</el-dialog> </el-dialog>
</template> </template>

View File

@ -1,14 +1,9 @@
<template> <template>
<el-container class="top is-dark"> <el-container class="top is-dark">
<!-- 图片上传 --> <!-- 图片上传 -->
<el-upload class="header__item" action="https://github.com/doocs/md" <el-tooltip :effect="effect" content="上传图片" placement="bottom-start">
:headers="{'Content-Type': 'multipart/form-data'}" <i class="el-icon-upload" size="medium" @click="$emit('showDialogUploadImg')"></i>
:show-file-list="false" :multiple="true" accept=".jpg,.jpeg,.png,.gif" name="file" </el-tooltip>
:before-upload="beforeUpload">
<el-tooltip :effect="effect" content="上传图片" placement="bottom-start">
<i class="el-icon-upload" size="medium"></i>
</el-tooltip>
</el-upload>
<!-- 下载文本文档 --> <!-- 下载文本文档 -->
<el-tooltip class="header__item" :effect="effect" content="下载编辑框Markdown文档" placement="bottom-start"> <el-tooltip class="header__item" :effect="effect" content="下载编辑框Markdown文档" placement="bottom-start">
<i class="el-icon-download" size="medium" @click="$emit('downLoad')"></i> <i class="el-icon-download" size="medium" @click="$emit('downLoad')"></i>
@ -76,7 +71,6 @@ import {
fixCodeWhiteSpace, fixCodeWhiteSpace,
setColorWithCustomTemplate setColorWithCustomTemplate
} from '../../assets/scripts/util' } from '../../assets/scripts/util'
import {uploadImgFile} from '../../assets/scripts/uploadImageFile';
import { import {
solveWeChatImage, solveWeChatImage,
solveHtml solveHtml
@ -106,7 +100,7 @@ export default {
return this.nightMode ? 'dark' : 'light' return this.nightMode ? 'dark' : 'light'
}, },
btnType() { btnType() {
return !this.nightMode ? 'success' : 'default'; return this.nightMode ? 'default' : 'primary';
}, },
...mapState({ ...mapState({
output: state => state.output, output: state => state.output,
@ -154,19 +148,6 @@ export default {
this.setCiteStatus(val) this.setCiteStatus(val)
this.$emit('refresh') this.$emit('refresh')
}, },
//
beforeUpload(file) {
uploadImgFile(file).then(res => {
this.$emit('uploaded', res)
}).catch(err => {
this.$message({
showClose: true,
message: err,
type: 'error'
});
});
return false;
},
// //
copy(e) { copy(e) {
this.$emit('startCopy'); this.$emit('startCopy');

View File

@ -73,7 +73,7 @@
}, },
computed: { computed: {
btnType() { btnType() {
return !this.nightMode ? "success" : "default"; return this.nightMode ? "default" : "primary";
}, },
...mapState({ ...mapState({
nightMode: state => state.nightMode, nightMode: state => state.nightMode,

View File

@ -21,7 +21,7 @@ export default {
}, },
computed: { computed: {
btnType() { btnType() {
return this.nightMode ? 'default' : 'success'; return this.nightMode ? 'default' : 'primary';
}, },
...mapState({ ...mapState({
nightMode: state => state.nightMode nightMode: state => state.nightMode

View File

@ -1,12 +1,7 @@
<template> <template>
<ul v-show="value" id="menu" class="menu" :style="`left: ${left}px;top: ${top}px;`"> <ul v-show="value" id="menu" class="menu" :style="`left: ${left}px;top: ${top}px;`">
<li v-for="item of list" :key="item.key" class="menu_item" @mousedown="onMouseDown(item.key)"> <li v-for="item of list" :key="item.key" class="menu_item" @mousedown="onMouseDown(item.key)">
<el-upload v-if="item.key === 'insertPic'" action="" class="li__upload" <span>{{item.text}}</span>
:show-file-list="false" :multiple="true" accept=".jpg,.jpeg,.png,.gif" name="file"
:before-upload="beforeUpload">
<button class="btn-upload">{{item.text}}</button>
</el-upload>
<span v-else>{{item.text}}</span>
</li> </li>
</ul> </ul>
</template> </template>
@ -56,27 +51,9 @@ export default {
closeCB() { closeCB() {
this.$emit('input', false); this.$emit('input', false);
}, },
// el-upload
//
beforeUpload(file) {
uploadImgFile(file).then(res => {
this.$emit('menuTick', 'insertPic', res)
}).catch(err => {
this.$message({
showClose: true,
message: err,
type: 'error'
});
});
return false;
},
onMouseDown(key){ onMouseDown(key){
if (key == 'insertPic') { this.$emit('menuTick', key)
document.querySelector('.li__upload button').click() this.$emit('closeMenu', false)
} else {
this.$emit('menuTick', key)
}
this.$emit('closeMenu', false)
} }
}, },
} }

View File

@ -0,0 +1,177 @@
<template>
<el-dialog title="插入图片" class="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-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"
></el-option>
</el-select>
<el-upload
drag
action
:headers="{'Content-Type': 'multipart/form-data'}"
:show-file-list="false"
:multiple="true"
accept=".jpg, .jpeg, .png, .gif"
name="file"
:before-upload="beforeUpload"
v-loading="uploadingImg"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处
<em>点击上传</em>
</div>
<!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件且不超过500kb</div> -->
</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="100px"
>
<el-form-item label="用户名:">
<el-input v-model="formGitHub.username"></el-input>
</el-form-item>
<el-form-item label="仓库名:">
<el-input v-model="formGitHub.repo"></el-input>
</el-form-item>
<el-form-item label="token:">
<el-input v-model="formGitHub.accessToken"></el-input>
</el-form-item>
<!-- <el-form-item label="jsDelivr CDN:">
<el-checkbox v-model="formGitHub.useCDN"></el-checkbox>
</el-form-item>-->
<el-form-item>
<el-button type="primary" @click="onSubmit">保存配置</el-button>
</el-form-item>
</el-form>
</el-tab-pane>
</el-tabs>
</el-dialog>
</template>
<script>
import { uploadImgFile } from "../../assets/scripts/uploadImageFile";
export default {
props: {
value: {
type: Boolean,
default: false,
},
},
data() {
return {
formGitHub: {
username: "",
repo: "",
accessToken: "",
// useCDN: true,
},
options: [
{
value: "default",
label: "默认图床",
},
{
value: "github",
label: "GitHub",
},
],
imgHost: "default",
uploadingImg: false,
};
},
created() {
if (localStorage.getItem("GitHubConfig")) {
this.formGitHub = JSON.parse(localStorage.getItem("GitHubConfig"));
}
if (localStorage.getItem("ImgHost")) {
this.imgHost = localStorage.getItem("ImgHost");
}
},
methods: {
changeImgHost() {
console.log("select img host:", this.imgHost);
localStorage.setItem("ImgHost", this.imgHost);
},
onSubmit() {
console.log("submit github params:", this.formGitHub);
localStorage.setItem("GitHubConfig", JSON.stringify(this.formGitHub));
this.$message({
message: "保存成功",
type: "success",
});
},
//
beforeUpload(file) {
if (!this.validateConfig()) {
return;
}
this.uploadingImg = true;
uploadImgFile(file)
.then((res) => {
this.$emit("uploaded", res);
this.uploadingImg = false;
})
.catch((err) => {
this.uploadingImg = false;
this.$message({
showClose: true,
message: err,
type: "error",
});
});
return false;
},
validateConfig() {
switch (this.imgHost) {
case "github":
const { username, repo, accessToken } = this.formGitHub;
if (!username || !repo || !accessToken) {
this.$message.error("未配置GitHub参数");
return false;
}
}
return true;
},
},
};
</script>
<style lang="less" scoped>
.upload-panel {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
.el-select {
align-self: flex-end;
margin: 0 67.75px 20px;
width: 100px;
}
}
.github-panel {
display: flex;
justify-content: center;
}
.setting-form {
width: 70%;
.el-form-item {
margin: 15px;
}
.el-form-item:last-child {
text-align: right;
}
}
</style>

View File

@ -5,12 +5,12 @@
<editor-header <editor-header
ref="header" ref="header"
@refresh="onEditorRefresh" @refresh="onEditorRefresh"
@uploaded="uploaded"
@cssChanged="cssChanged" @cssChanged="cssChanged"
@downLoad="downloadEditorContent" @downLoad="downloadEditorContent"
@showCssEditor="showCssEditor = !showCssEditor" @showCssEditor="showCssEditor = !showCssEditor"
@showAboutDialog="aboutDialogVisible = true" @showAboutDialog="aboutDialogVisible = true"
@showDialogForm="dialogFormVisible = true" @showDialogForm="dialogFormVisible = true"
@showDialogUploadImg="dialogUploadImgVisible = true"
@startCopy="isCoping = true, backLight = true" @startCopy="isCoping = true, backLight = true"
@endCopy="endCopy" @endCopy="endCopy"
/> />
@ -42,6 +42,7 @@
</el-row> </el-row>
</el-main> </el-main>
</el-container> </el-container>
<upload-img-dialog v-model="dialogUploadImgVisible" @close="dialogUploadImgVisible = false" @uploaded="uploaded" />
<about-dialog v-model="aboutDialogVisible"/> <about-dialog v-model="aboutDialogVisible"/>
<insert-form-dialog v-model="dialogFormVisible"/> <insert-form-dialog v-model="dialogFormVisible"/>
<right-click-menu <right-click-menu
@ -58,6 +59,8 @@ import editorHeader from '../components/CodemirrorEditor/header';
import aboutDialog from '../components/CodemirrorEditor/aboutDialog'; import aboutDialog from '../components/CodemirrorEditor/aboutDialog';
import insertFormDialog from '../components/CodemirrorEditor/insertForm'; import insertFormDialog from '../components/CodemirrorEditor/insertForm';
import rightClickMenu from '../components/CodemirrorEditor/rightClickMenu'; import rightClickMenu from '../components/CodemirrorEditor/rightClickMenu';
import uploadImgDialog from '../components/CodemirrorEditor/uploadImgDialog';
import { import {
css2json, css2json,
downLoadMD, downLoadMD,
@ -74,6 +77,7 @@ export default {
return { return {
showCssEditor: false, showCssEditor: false,
aboutDialogVisible: false, aboutDialogVisible: false,
dialogUploadImgVisible: false,
dialogFormVisible: false, dialogFormVisible: false,
isCoping: false, isCoping: false,
isImgLoading: false, isImgLoading: false,
@ -89,7 +93,8 @@ export default {
editorHeader, editorHeader,
aboutDialog, aboutDialog,
insertFormDialog, insertFormDialog,
rightClickMenu rightClickMenu,
uploadImgDialog
}, },
computed: { computed: {
...mapState({ ...mapState({
@ -191,6 +196,7 @@ export default {
}); });
return; return;
} }
this.dialogUploadImgVisible = false
// //
const cursor = this.editor.getCursor(); const cursor = this.editor.getCursor();
const imageUrl = response; const imageUrl = response;
@ -277,7 +283,7 @@ export default {
this.$refs.header.showResetConfirm = true; this.$refs.header.showResetConfirm = true;
break; break;
case 'insertPic': case 'insertPic':
this.uploaded(info); this.dialogUploadImgVisible = true
break; break;
case 'downLoad': case 'downLoad':
this.downloadEditorContent(); this.downloadEditorContent();