Merge pull request #50 from doocs/feature_upload-component_20201204

Feature upload component 20201204
This commit is contained in:
Yang Libin 2020-12-05 21:25:30 +08:00 committed by GitHub
commit b91613e176
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 115 additions and 152 deletions

View File

@ -1,35 +0,0 @@
import fileApi from "../../api/file";
export function uploadImgFile(file) {
return new Promise((resolve, reject) => {
const checkImageResult = isImageIllegal(file);
if (checkImageResult) {
reject(checkImageResult);
return;
}
const base64Reader = new FileReader();
base64Reader.readAsDataURL(file);
base64Reader.onload = function () {
const base64Content = this.result.split(",").pop();
fileApi
.fileUpload(base64Content, file)
.then((res) => {
resolve(res);
})
.catch((err) => {
reject(err);
});
};
});
}
export function isImageIllegal(file) {
if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.name)) {
return "请上传 JPG/PNG/GIF 格式的图片";
}
if (file.size > 5 * 1024 * 1024) {
return "由于公众号限制,图片大小不能超过 5.0M";
}
return false;
}

View File

@ -263,3 +263,33 @@ export function createTable({ data, rows, cols }) {
return table; return table;
} }
export const toBase64 = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result.split(",").pop());
reader.onerror = (error) => reject(error);
});
export function checkImage(file) {
// check filename suffix
const isValidSuffix = /\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.name);
if (!isValidSuffix) {
return {
ok: false,
msg: "请上传 JPG/PNG/GIF 格式的图片",
};
}
// check file size
const maxSize = 5;
const isLt5M = file.size / 1024 / 1024 <= maxSize;
if (!isLt5M) {
return {
ok: false,
msg: `由于公众号限制,图片大小不能超过 ${maxSize}M`,
};
}
return { ok: true };
}

View File

@ -48,7 +48,7 @@
<i <i
class="el-icon-s-grid" class="el-icon-s-grid"
size="medium" size="medium"
@click="$emit('showDialogForm')" @click="$emit('show-dialog-form')"
></i> ></i>
</el-tooltip> </el-tooltip>
<el-form size="mini" class="ctrl" :inline="true"> <el-form size="mini" class="ctrl" :inline="true">

View File

@ -19,7 +19,6 @@
</template> </template>
<script> <script>
import { uploadImgFile } from "../../assets/scripts/uploadImageFile";
export default { export default {
props: { props: {
value: { value: {

View File

@ -29,8 +29,8 @@
:multiple="true" :multiple="true"
accept=".jpg, .jpeg, .png, .gif" accept=".jpg, .jpeg, .png, .gif"
name="file" name="file"
:before-upload="beforeUpload" :before-upload="beforeImageUpload"
v-loading="uploadingImg" :http-request="uploadImage"
> >
<i class="el-icon-upload"></i> <i class="el-icon-upload"></i>
<div class="el-upload__text"> <div class="el-upload__text">
@ -304,7 +304,7 @@
</template> </template>
<script> <script>
import { uploadImgFile } from "../../assets/scripts/uploadImageFile"; import { checkImage } from "../../assets/scripts/util";
export default { export default {
props: { props: {
@ -375,7 +375,6 @@ export default {
}, },
], ],
imgHost: "default", imgHost: "default",
uploadingImg: false,
}; };
}, },
created() { created() {
@ -398,50 +397,32 @@ export default {
methods: { methods: {
changeImgHost() { changeImgHost() {
localStorage.setItem("imgHost", this.imgHost); localStorage.setItem("imgHost", this.imgHost);
this.$message({ this.$message.success("已成功切换图床");
showClose: true,
message: "已成功切换图床",
type: "success",
});
}, },
saveGitHubConfiguration() { saveGitHubConfiguration() {
if (!(this.formGitHub.repo && this.formGitHub.accessToken)) { if (!(this.formGitHub.repo && this.formGitHub.accessToken)) {
const blankElement = this.formGitHub.repo const blankElement = this.formGitHub.repo
? "token" ? "token"
: "GitHub 仓库"; : "GitHub 仓库";
this.$message({ this.$message.error(`参数「​${blankElement}」不能为空`);
showClose: true,
message: `参数「​${blankElement}」不能为空`,
type: "error",
});
return; return;
} }
localStorage.setItem( localStorage.setItem(
"githubConfig", "githubConfig",
JSON.stringify(this.formGitHub) JSON.stringify(this.formGitHub)
); );
this.$message({ this.$message.success("保存成功");
message: "保存成功",
type: "success",
});
}, },
saveGiteeConfiguration() { saveGiteeConfiguration() {
if (!(this.formGitee.repo && this.formGitee.accessToken)) { if (!(this.formGitee.repo && this.formGitee.accessToken)) {
const blankElement = this.formGitee.repo const blankElement = this.formGitee.repo
? "私人令牌" ? "私人令牌"
: "Gitee 仓库"; : "Gitee 仓库";
this.$message({ this.$message.error(`参数「​${blankElement}」不能为空`);
showClose: true,
message: `参数「​${blankElement}」不能为空`,
type: "error",
});
return; return;
} }
localStorage.setItem("giteeConfig", JSON.stringify(this.formGitee)); localStorage.setItem("giteeConfig", JSON.stringify(this.formGitee));
this.$message({ this.$message.success("保存成功");
message: "保存成功",
type: "success",
});
}, },
saveAliOSSConfiguration() { saveAliOSSConfiguration() {
if ( if (
@ -452,21 +433,14 @@ export default {
this.formAliOSS.region this.formAliOSS.region
) )
) { ) {
this.$message({ this.$message.error(`阿里云 OSS 参数配置不全`);
showClose: true,
message: `阿里云 OSS 参数配置不全`,
type: "error",
});
return; return;
} }
localStorage.setItem( localStorage.setItem(
"aliOSSConfig", "aliOSSConfig",
JSON.stringify(this.formAliOSS) JSON.stringify(this.formAliOSS)
); );
this.$message({ this.$message.success("保存成功");
message: "保存成功",
type: "success",
});
}, },
saveTxCOSConfiguration() { saveTxCOSConfiguration() {
@ -478,18 +452,11 @@ export default {
this.formTxCOS.region this.formTxCOS.region
) )
) { ) {
this.$message({ this.$message.error(`腾讯云 COS 参数配置不全`);
showClose: true,
message: `腾讯云 COS 参数配置不全`,
type: "error",
});
return; return;
} }
localStorage.setItem("txCOSConfig", JSON.stringify(this.formTxCOS)); localStorage.setItem("txCOSConfig", JSON.stringify(this.formTxCOS));
this.$message({ this.$message.success("保存成功");
message: "保存成功",
type: "success",
});
}, },
saveQiniuConfiguration() { saveQiniuConfiguration() {
@ -502,44 +469,35 @@ export default {
this.formQiniu.region this.formQiniu.region
) )
) { ) {
this.$message({ this.$message.error(`七牛云 Kodo 参数配置不全`);
showClose: true,
message: `七牛云 Kodo 参数配置不全`,
type: "error",
});
return; return;
} }
localStorage.setItem("qiniuConfig", JSON.stringify(this.formQiniu)); localStorage.setItem("qiniuConfig", JSON.stringify(this.formQiniu));
this.$message({ this.$message.success("保存成功");
message: "保存成功",
type: "success",
});
}, },
// beforeImageUpload(file) {
beforeUpload(file) { // check image
const imgHost = localStorage.getItem("imgHost"); const checkResult = checkImage(file);
if (!checkResult.ok) {
this.$message.error(checkResult.msg);
return false;
}
// check image host
let imgHost = localStorage.getItem("imgHost");
imgHost = imgHost ? imgHost : "default";
localStorage.setItem("imgHost", imgHost);
const config = localStorage.getItem(`${imgHost}Config`); const config = localStorage.getItem(`${imgHost}Config`);
if (!config && imgHost !== "" && imgHost !== "default") { const isValidHost = imgHost == "default" || config;
if (!isValidHost) {
this.$message.error(`请先配置 ${imgHost} 图床参数`); this.$message.error(`请先配置 ${imgHost} 图床参数`);
return false; return false;
} }
return true;
this.uploadingImg = true; },
uploadImgFile(file) uploadImage(params) {
.then((res) => { this.$emit("uploadImage", params.file);
this.$emit("uploaded", res);
this.uploadingImg = false;
})
.catch((err) => {
this.uploadingImg = false;
this.$message({
showClose: true,
message: err,
type: "error",
});
});
return false;
}, },
}, },
}; };

View File

@ -5,7 +5,6 @@ import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css"; import "element-ui/lib/theme-chalk/index.css";
import "./plugins/element"; import "./plugins/element";
import "codemirror/lib/codemirror.css"; import "codemirror/lib/codemirror.css";
import "codemirror/theme/ambiance.css";
import "codemirror/theme/xq-light.css"; import "codemirror/theme/xq-light.css";
import "codemirror/mode/css/css"; import "codemirror/mode/css/css";
import "codemirror/mode/markdown/markdown"; import "codemirror/mode/markdown/markdown";

View File

@ -152,7 +152,6 @@ const mutations = {
}, },
clearEditorToDefault(state) { clearEditorToDefault(state) {
const doc = formatDoc(DEFAULT_CONTENT); const doc = formatDoc(DEFAULT_CONTENT);
state.editor.setValue(doc); state.editor.setValue(doc);
state.cssEditor.setValue(DEFAULT_CSS_CONTENT); state.cssEditor.setValue(DEFAULT_CSS_CONTENT);
}, },

View File

@ -9,7 +9,7 @@
@download="downloadEditorContent" @download="downloadEditorContent"
@showCssEditor="showCssEditor = !showCssEditor" @showCssEditor="showCssEditor = !showCssEditor"
@show-about-dialog="aboutDialogVisible = true" @show-about-dialog="aboutDialogVisible = true"
@showDialogForm="dialogFormVisible = true" @show-dialog-form="dialogFormVisible = true"
@show-dialog-upload-img="dialogUploadImgVisible = true" @show-dialog-upload-img="dialogUploadImgVisible = true"
@startCopy="(isCoping = true), (backLight = true)" @startCopy="(isCoping = true), (backLight = true)"
@endCopy="endCopy" @endCopy="endCopy"
@ -73,6 +73,8 @@
<upload-img-dialog <upload-img-dialog
v-model="dialogUploadImgVisible" v-model="dialogUploadImgVisible"
@close="dialogUploadImgVisible = false" @close="dialogUploadImgVisible = false"
@beforeUpload="beforeUpload"
@uploadImage="uploadImage"
@uploaded="uploaded" @uploaded="uploaded"
/> />
<about-dialog v-model="aboutDialogVisible" /> <about-dialog v-model="aboutDialogVisible" />
@ -100,8 +102,11 @@ import {
setFontSize, setFontSize,
saveEditorContent, saveEditorContent,
customCssWithTemplate, customCssWithTemplate,
checkImage,
} from "../assets/scripts/util"; } from "../assets/scripts/util";
import { uploadImgFile } from "../assets/scripts/uploadImageFile";
import { toBase64 } from "../assets/scripts/util";
import fileApi from "../api/file";
require("codemirror/mode/javascript/javascript"); require("codemirror/mode/javascript/javascript");
import { mapState, mapMutations } from "vuex"; import { mapState, mapMutations } from "vuex";
@ -174,37 +179,14 @@ export default {
++i ++i
) { ) {
let item = e.clipboardData.items[i]; let item = e.clipboardData.items[i];
if (item.kind === "file") { if (item.kind === "file") {
// //
const imgHost = const pasteFile = item.getAsFile();
localStorage.getItem("imgHost") || "default"; const isValid = this.beforeUpload(pasteFile);
if ( if (!isValid) {
imgHost != "default" &&
!localStorage.getItem(`${imgHost}Config`)
) {
this.$message({
showClose: true,
message: "请先配置好图床参数",
type: "error",
});
continue; continue;
} }
this.uploadImage(pasteFile);
this.isImgLoading = true;
const pasteFile = item.getAsFile();
uploadImgFile(pasteFile)
.then((res) => {
this.uploaded(res);
})
.catch((err) => {
this.$message({
showClose: true,
message: err,
type: "error",
});
});
this.isImgLoading = false;
} }
} }
}); });
@ -243,14 +225,49 @@ export default {
}); });
this.onEditorRefresh(); this.onEditorRefresh();
}, },
beforeUpload(file) {
// validate image
const checkResult = checkImage(file);
if (!checkResult.ok) {
this.$message.error(checkResult.msg);
return false;
}
// check image host
let imgHost = localStorage.getItem("imgHost");
imgHost = imgHost ? imgHost : "default";
localStorage.setItem("imgHost", imgHost);
const config = localStorage.getItem(`${imgHost}Config`);
const isValidHost = imgHost == "default" || config;
if (!isValidHost) {
this.$message.error(`请先配置 ${imgHost} 图床参数`);
return false;
}
return true;
},
uploadImage(file) {
this.isImgLoading = true;
toBase64(file)
.then((base64Content) => {
fileApi
.fileUpload(base64Content, file)
.then((url) => {
this.uploaded(url);
})
.catch((err) => {
this.$message.error(err.message);
});
})
.catch((err) => {
this.$message.error(err.message);
});
this.isImgLoading = false;
},
// //
uploaded(response) { uploaded(response) {
if (!response) { if (!response) {
this.$message({ this.$message.error("上传图片未知异常");
showClose: true,
message: "上传图片未知异常",
type: "error",
});
return; return;
} }
this.dialogUploadImgVisible = false; this.dialogUploadImgVisible = false;
@ -260,11 +277,7 @@ export default {
const markdownImage = `![](${imageUrl})`; const markdownImage = `![](${imageUrl})`;
// Markdown URL // Markdown URL
this.editor.replaceSelection(`\n${markdownImage}\n`, cursor); this.editor.replaceSelection(`\n${markdownImage}\n`, cursor);
this.$message({ this.$message.success("图片上传成功");
showClose: true,
message: "图片上传成功",
type: "success",
});
this.onEditorRefresh(); this.onEditorRefresh();
}, },
// //