UploadItem.vue 2.94 KB
<template>
    <!-- list-type="picture-card" -->
    <!-- :limit="limit ? limit : 1" -->
    <el-upload
        action="''"
        :multiple="multiple ? true : false"
        :accept="accept ? accept : 'image/*'"
        :list-type="listtype ? listtype : 'picture'"
        :show-file-list="showlist ? true : false"
        :http-request="upload"
        :before-upload="beforeAvatarUpload"
    >
        <!-- <i class="el-icon-plus"></i> -->
        <el-button size="small" type="primary" :disabled="uploading">{{uploading? '正在上传':'点击上传'}}</el-button>
        <div slot="tip" class="el-upload__tip">{{tips}}</div>
    </el-upload>
</template>


<script>
import { uploadFile } from '../api/api.js'

export default {
    name: 'uploadfile',
    // 上传多图片
    // accept 接受类型  图片:image/*  视频:video/*
    props: [
        'pid',
        'multiple',
        'accept',
        'limit',
        'listtype',
        'tips',
        'showlist'
    ],
    data() {
        return {
            config: {
                maxSizeData: {
                    image: 2, //图片不大于2M
                    video: 20 //视频不大于20M
                }
            },
            uploading: false,
            file: {}
        }
    },
    created() {},
    methods: {
        getMaxSizeByType(file) {
            let result = 2
            if (file && file.type) {
                let type = file.type
                if (type.indexOf('image') != -1) {
                    return this.config.maxSizeData.image
                } else if (type.indexOf('video') != -1) {
                    return this.config.maxSizeData.video
                }
            }
            return result
        },
        // 图片上传前验证
        beforeAvatarUpload(file) {
            let maxSize = this.getMaxSizeByType(file)
            const isLt = file.size / 1024 / 1024 < maxSize
            if (!isLt) {
                this.$message.error(`该文件大小不能超过${maxSize}MB!`)
            }
            return isLt
        },
        // 上传图片到OSS 同时派发一个事件给父组件监听
        upload(file) {
            // 返回图片的存储路径 开始上传
            this.uploading = true
            this.file = file
            let params = new FormData() //使用formData对象
            params.append('path', '/pro/mzczcradmin/')
            params.append('file', file.file)
            uploadFile(params)
                .then(result => {
                    let url = result.content
                    // 返回图片的存储路径
                    this.$emit('upload-success', {
                        pid: this.pid,
                        url: url
                    })
                    this.uploading = false
                })
                .catch(err => {
                    this.uploading = false
                })
            return
        }
    }
}
</script>

<style lang="less" scoped>
.el-upload-list {
}
</style>