123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- <template>
- <el-upload
- class="upload-button"
- :action="uploadUrl"
- :max-size="maxSize"
- :before-upload="handleBeforeUpload"
- :show-file-list="showFileList"
- :auto-upload="autoUpload"
- :disabled="disabled"
- ref="UploadComp"
- :onChange="onChange"
- :onRemove="onRemove"
- :multiple="false"
- :fileList="fileList"
- >
- <el-button :type="theme" :disabled="disabled" :loading="loading">{{
- btnContent
- }}</el-button>
- </el-upload>
- </template>
- <script>
- import { fileMD5 } from "@/plugins/md5";
- export default {
- name: "upload-button",
- props: {
- btnContent: {
- type: String,
- default: "选择",
- },
- format: {
- type: Array,
- default() {
- return ["jpg", "png"];
- },
- },
- maxSize: {
- type: Number,
- default: 20 * 1024 * 1024,
- },
- disabled: {
- type: Boolean,
- default: false,
- },
- theme: {
- type: String,
- default: "primary",
- },
- showFileList: {
- type: Boolean,
- default: false,
- },
- autoUpload: {
- type: Boolean,
- default: true,
- },
- },
- data() {
- return {
- loading: false,
- uploadUrl: "",
- res: {},
- fileList: [],
- };
- },
- methods: {
- checkFileFormat(fileType) {
- const _file_format = fileType.split(".").pop().toLocaleLowerCase();
- if (!this.format.length) return true;
- return this.format.some(
- (item) => item.toLocaleLowerCase() === _file_format
- );
- },
- async handleBeforeUpload(file) {
- this.attachmentName = file.name;
- if (file.size > this.maxSize) {
- this.handleExceededSize();
- return Promise.reject();
- }
- if (!this.checkFileFormat(file.name)) {
- this.handleFormatError();
- return Promise.reject();
- }
- return true;
- },
- handleFormatError() {
- const content = "只支持文件格式为" + this.format.join("/");
- this.res = {
- success: false,
- message: content,
- };
- this.loading = false;
- this.$emit("upload-error", this.res);
- },
- handleExceededSize() {
- const content =
- "文件大小不能超过" + Math.floor(this.maxSize / 1024) + "M";
- this.res = {
- success: false,
- message: content,
- };
- this.loading = false;
- this.$emit("upload-error", this.res);
- },
- async onChange(file, fileList) {
- console.log("onChange", file, fileList);
- this.fileList = [file];
- const md5 = await fileMD5(file.raw);
- this.$emit("file-change", {
- file: file.raw,
- md5,
- });
- },
- onRemove(file, fileList) {
- console.log("remove", file, fileList);
- if (!fileList.length) {
- this.$emit("file-change", { file: null, md5: null });
- }
- },
- },
- };
- </script>
- <style lang="scss">
- .upload-button {
- .el-upload {
- width: auto !important;
- }
- }
- </style>
|