index.vue 14.1 KB
<template>
    <div>

        <div :class="disabled ? 'k-upload-dragger disabledStyle' : 'k-upload-dragger noDisabledStyle'" id="aaaa" @paste="pasteImg">
            <div>
                <div class="upload-label">
                    <slot></slot>
                </div>
                <div class="k-upload-content">

                    <div class="img-content" v-if="imgUrl != '' && type == 'edit'"
                        :style="{ height: newHeight + 'px', width: newWidth + 'px' }">
                        <img @click="removeImg()" class="imgDelete" src="../../assets/images/delete.svg" alt=""
                            style="z-index: 2;position:absolute; top:-5px ; right: -5px ; cursor: pointer;" />

                        <el-image :style="{ height: newHeight + 'px', width: newWidth + 'px' }" :src="imgUrl" fit="contain"
                            @load="imgload"></el-image>
                    </div>
                    <div class="img-content" v-if="imageBase != '' && type == 'view'"
                        :style="{ height: newHeight + 'px', width: newWidth + 'px' }">
                        <el-image :style="{ height: newHeight + 'px', width: newWidth + 'px' }" :src="imageBase"
                            fit="contain" @load="imgload"></el-image>
                    </div>
                    <div v-if="imgUrl == '' && disabled == false && type == 'edit'">
                        <i class="el-icon-upload"></i>
                        <div class="k-upload-dragger-text">
                            <el-upload ref="uploadRef" action="" :file-list="fileList" style="display: inline-block;"
                                :auto-upload="false" :show-file-list="false" :disabled="disabled" :http-reques="uploadFile"
                                :on-change="handFileChange" accept="image/jpg,image/jpeg,image/png,image/bmp">
                                <span class="uploadTip">將文件粘貼到此處或</span><em>點擊上傳</em>
                            </el-upload>
                            <div class="tipText">(圖片格式僅支持bmp,jpg,jpeg,png格式,大小不超過2M)</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- <div class="tipText" v-if="showTip">只能上传bmp/jpg/jpeg/png文件,且不超过2MB</div> -->

    </div>
</template>
<script>
import { debounce } from '@/utils/index.js' 
export default {
    props: {
        disabled: {
            type: Boolean,
            default: false,
        },
        imageBase: {
            type: String,
            default: "",
        },
        type: {
            type: String,
            default: "edit",
        }

    },
    data() {
        return {
            imgUrl: "",
            newWidth: 0,
            checkpoint:new Date().getTime(),
            newHeight: 0,
            fileList: [],
            imageSelect: 2,
            showTip: false,
            fileName: null,
            fileSize: null,
            lastMethodTimestamp: null,
            pasteEvnet:true,
        }
    }, watch: {
        fileList(newVal) {
            // console.log(newVal);
        },
        imageBase(val) {
            if (val) {
                this.imgUrl = "data:image/jpeg;base64," + val;
            } else {
                this.imgUrl = "";
            }
        }, disabled(val) {
            if (val) {
                this.imgUrl = "";
            }
        }

    },
    mounted() {

        // var btn = document.getElementById('aaaa');
        // btn.addEventListener('paste', event => {
        //     var items = (event.clipboardData || event.originalEvent.clipboardData).items;
        //         if (items.length > 0 && items[0].type.indexOf('image') !== -1) {
        //             var blob = items[0].getAsFile();

        //             const now = Date.now();
        //             if (!this.lastMethodTimestamp || now - this.lastMethodTimestamp >= 1000) {
        //                 this.lastMethodTimestamp = now;
        //                 this.timer = setTimeout(() => {
        //                     this.lastMethodTimestamp = null;
        //                     clearTimeout(this.timer);
        //                 }, 1000);

        //                 var checkRes = this.checkImage(blob);
        //                 if (!checkRes) {
        //                     this.$message.warning("圖片格式僅支持bmp,jpg,jpeg,png格式,大小不超過2M。");
        //                     this.showTip = true;

        //                 } else {

        //                     this.getBase64(blob).then(res => {
        //                         const params = res.split(',')
        //                         if (params.length > 0) {
        //                             this.imgUrl = params[0] + "," + params[1];
        //                         }
        //                     })
        //                     this.imageSelect = 1;
        //                     this.$emit("uploadFileInfo", { file: blob, imageSelect: this.imageSelect });
        //                 }

        //                 } else {

        //                     // 处理重复触发的情况
        //                 }
        //         }
        // }, false);

        // aaaa.paste = function () {  console.log(7777); };
        // window.onpaste = function (event) {
        //     console.log(7777);
        // }
        // 监听 ctrl+v键盘事件
        // document.body.addEventListener('paste', event => {
        //     console.log(new Date().getTime());
        //     // if (this.pasteEvnet) {
        //     //     this.pasteEvnet = false;
        //     //     this.pasteImg(event);
        //     // }

        // });
    }, methods: {
        uploadFile(files) {
            // console.log(12321);

        }, filePreview(e) {
            let file = e.target.files[0];
            let url = "";
            var reader = new FileReader();
            reader.readAsDataURL(file);
            let that = this;
            reader.onload = function (e) {
                url = this.result.substring(this.result.indexOf(",") + 1);
                that.imgUrl = "data:image/png;base64," + url;
            };
        }, removeImg() {
            this.imgUrl = "";
            this.imageSelect = 1;
            this.$emit("uploadFileInfo", { file: null, imageSelect: this.imageSelect });
        }, imgload(e) {
            const origWidth = e.target.naturalWidth;
            const origHeight = e.target.naturalHeight;

            if (origWidth > origHeight) {
                this.newWidth = 200;
                this.newHeight = (this.newWidth * origHeight) / origWidth;
            } else if (origWidth < origHeight) {
                this.newHeight = 200;
                this.newWidth = ((this.newHeight * origWidth) / origHeight);

            } else {
                this.newWidth = 200;
                this.newHeight = 200;
            }
        },
        submitUpload() {
            this.$refs.uploadRef.submit();
        }, handFileChange(file) {

            var checkRes = this.checkImage(file);
            if (!checkRes) {
                this.$message.warning("圖片格式僅支持bmp,jpg,jpeg,png格式,大小不超過2M。");
                this.showTip = true;
            } else {
                this.showTip = false;

                this.imageSelect = 1;
                this.getBase64(file.raw).then(res => {
                    const params = res.split(',')
                    // console.log(params, 'params')
                    if (params.length > 0) {
                        this.imgUrl = params[0] + "," + params[1];
                    }
                })
                // const _file = file.raw;
                // const myBlob = new Blob([_file], { type: 'multipart/form-data;charset=UTF-8' });
                // const qrUrl = window.URL.createObjectURL(myBlob)
                // this.imgUrl = qrUrl;
                this.$emit("uploadFileInfo", { file: file.raw, imageSelect: this.imageSelect });
            }
        },
        checkImage(file) {
            var img = file.name.substring(file.name.lastIndexOf('.') + 1);
            const suffix = img.toLowerCase() === 'jpg';
            const suffix2 = img.toLowerCase() === 'png';
            const suffix3 = img.toLowerCase() === 'jpeg';
            const suffix4 = img.toLowerCase() === 'bmp';
            const isLt1M = file.size / 1024 / 1024 < 2;

            return !((!suffix && !suffix2 && !suffix3 && !suffix4) || !isLt1M);
        },// 获取图片转base64
        getBase64(file) {
            return new Promise(function (resolve, reject) {
                const reader = new FileReader()
                let imgResult = ''
                reader.readAsDataURL(file)
                reader.onload = function () {
                    imgResult = reader.result
                }
                reader.onerror = function (error) {
                    reject(error)
                }
                reader.onloadend = function () {
                    resolve(imgResult)
                }
            })
        },// 封装节流函数
        throttle(fn, time) {
            return new Promise((resolve, reject) => {
                //3. 通过闭包保存一个 "节流阀" 默认为false
                let temp = false;
                //8.触发事件被调用 判断"节流阀" 是否为true  如果为true就直接trurn出去不做任何操作
                if (temp) {
                    resolve();
                } else {
                    //4. 如果节流阀为false  立即将节流阀设置为true
                    temp = true; //节流阀设置为true
                    //5.  开启定时器
                    setTimeout(() => {
                        //6. 将外部传入的函数的执行放在setTimeout中
                        fn.apply(this, arguments);
                        //7. 最后在setTimeout执行完毕后再把标记'节流阀'为false(关键)  表示可以执行下一次循环了。当定时器没有执行的时候标记永远是true,在开头被return掉
                        temp = false;
                    }, time);
                }

            });

        },
        pasteImg(event) {
            if (this.disabled) {
                return;
            }
            console.log("checkpoint:" + this.checkpoint);
            console.log("now:" + new Date().getTime());
            var diff = new Date().getTime() - this.checkpoint;
            console.log(diff);

            if (diff < 1500) {
                console.log("return");
                return;
            } else {
                console.log("paste");
                this.checkpoint = new Date().getTime();
                var items = (event.clipboardData || event.originalEvent.clipboardData).items;
                if (items.length > 0 && items[0].type.indexOf('image') !== -1) {
                    var blob = items[0].getAsFile();
                    // console.log(new Date());
                    // // console.log(blob.size);
                    // if(blob.name==this.fileName && blob.size==this.size){
                    //     return;
                    // }else{
                    //   this.fileName=blob.name;
                    //   this.size=blob.size;
                    // }
                    // const now = Date.now();
                    // if (!this.lastMethodTimestamp || now - this.lastMethodTimestamp >= 1000) {
                    //     this.lastMethodTimestamp = now;
                    //     this.timer = setTimeout(() => {
                    //         this.lastMethodTimestamp = null;
                    //         clearTimeout(this.timer);
                    //     }, 1000);

                    var checkRes = this.checkImage(blob);
                    if (!checkRes) {
                        this.$message.warning("圖片格式僅支持bmp,jpg,jpeg,png格式,大小不超過2M。");
                        this.showTip = true;
                        // let timer1 = setTimeout(() => {
                        //     this.pasteEvnet = true;
                        //     clearTimeout(timer1);
                        // }, 2000);

                    } else {
                        this.getBase64(blob).then(res => {
                            const params = res.split(',')
                            // console.log(params, 'params')
                            if (params.length > 0) {
                                this.imgUrl = params[0] + "," + params[1];
                            }
                        })
                        this.imageSelect = 1;
                        // this.$emit("imgBlob", blob);
                        this.$emit("uploadFileInfo", { file: blob, imageSelect: this.imageSelect });

                        let timer2 = setTimeout(() => {
                            this.pasteEvnet = true;
                            clearTimeout(timer2);
                        }, 2000);
                    }

                    // } 
                }
            }
            
        }

    }

}
</script>
<style scoped lang="scss">
.disabledStyle {
    cursor: no-drop;

    em {
        cursor: no-drop;
        color: #409eff;
        font-style: normal;
    }

    .upload-label {
        color: #8E8E8E;
    }
}

.noDisabledStyle {
    em {
        cursor: pointer;
        color: #409eff;
        font-style: normal;
    }

    .upload-label {
        color: #333;
    }
}

.k-upload-dragger {
    background-color: #F2F2F2;
    // border: 1px dashed #d9d9d9;
    // border-radius: 6px;
    box-sizing: border-box;
    // width: 360px;
    height: 210px;
    display: flex;
    // cursor: pointer;
    align-items: center;
    justify-content: center;

    position: relative;

    .k-upload-content {
        text-align: center;
        color: #606266;

        .el-icon-upload {
            font-size: 50px;
        }

    }

    .upload-label {
        font-weight: 700;
        font-size: 0.75rem;
        position: absolute;
        top: 10px;
        left: 10px;
    }
}

.img-content {
    width: 200px;
    height: 200px;
    position: relative;

}

.tipText {
    display: block;
    margin-top: 3px;
    padding: 0 0.9375rem;
    font-size: 12px;
    color: #999;
}

.uploadTip {
    color: #606266;
}
</style>