基于iview upload组件封装上传图片功能

  • Post author:
  • Post category:其他


<template>
    <div class="upload-list-box">
        <div class="upload-list" v-for="(item,index) in uploadList" :key="index">
            <template v-if="item.status === 'finished'">
                <img :src="ossPath+item.imageFileName">
                <div class="upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.imageFileName)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="handleRemove(item)" v-if="!isDisable"></Icon>
                </div>
            </template>
            <template v-else>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
        </div>
        <Upload            
            ref="upload"
            :show-upload-list="false"
            :default-file-list="defaultList"
            :on-success="handleSuccess"
            :format="['jpg','jpeg','png', 'gif','webp']"
            :max-size="500"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :before-upload="handleBeforeUpload"
            multiple
            type="drag"
            :action="action"
            name="file"
            :data="formData"
            v-show="uploadList.length<maxLength"
        >
            <div class="upload-btn">
                <Icon type="ios-camera" size="35"></Icon>
            </div>
        </Upload>
        <Modal title="图片预览" v-model="visible">
            <img :src="ossPath+imageFileName" v-if="visible" style="width: 100%">
        </Modal>
    </div>
</template>
<script type="text/javascript">
	import Api from 'api/index';
	import md5 from 'js-md5';
	import * as common from 'common/common';

    export default {
        props: ['defaultList', 'maxLength', 'activityValidate', 'isDisable'],
        data() {
            return {   
                imageFileName: '',
                action: '',
                visible: false,
                uploadList: [],
                formData: {},
                ossPath: vueApp.config.ossPath,
            }
        },
        components: {

        },
        watch:{
            // "defaultList":function(vals){
            //     console.log('this',vals)
            //     // this.uploadList = this.$refs.upload.fileList;
            //     console.log('---this.uploadList', this.uploadList);
            // }
        },
        methods: {
            // 预览图片
            handleView (name) {
                this.imageFileName = name;
                this.visible = true;
            },
            // 删除图片
            handleRemove (file) {
                console.log(file);
                const fileList = this.uploadList;
                this.uploadList.splice(fileList.indexOf(file), 1);
                this.callbackFun();
            },
            // 上传成功
            handleSuccess(res, file) {
                console.log(res,file);
                if( res.success ){
                    file.imageFileName = res.result.url;
                    this.callbackFun();
                }else{
                    this.$Notice.warning({
                        title: res.msg
                    });
                }
            },
            // 上传错误
            handleFormatError (file) {
                this.$Notice.warning({
                    title: '文件格式不正确',
                    desc: file.name + ' 文件格式不正确, 请选择jpg、jpeg、png、gif格式图片!'
                });
            },
            // 超过大小限制
            handleMaxSize (file) {
                this.$Notice.warning({
                    title: '超过文件大小限制',
                    desc: file.name + ' 图片文件太大, 不超过 500KB!',
                    
                });
            },
            // 上传之前校验
            async handleBeforeUpload (file) {
                console.log('file', file);
                let check = this.uploadList.length < this.maxLength;
                if( !check ) {
                    this.$Notice.warning({
                        title: '最多可以上传'+this.maxLength+'张照片!'
                    });
                    return false;
                }else{
                    await Api.fileSign().then(res=>{
                        if( res.success ){
                            let ossKey = res.result;
                            this.action = ossKey.host;
                            this.formData = {
                                OSSAccessKeyId: ossKey.accessid,
                                callback: ossKey.callback,
                                policy: ossKey.policy,
                                signature: ossKey.signature,
                                key: (ossKey.dir+'carclub/'+md5(new Date()+file.name)+common.getValidate(file.name)),
                                success_action_status: '200',
                                secure: true
                            }
                        }
                    });
                    return true;
                }
            },
            // 遍历图片
            forUploadImg(){
                let imgArr = [];
                this.uploadList.forEach(item=>{
                    imgArr.push(item.imageFileName);
                });
                return imgArr;
            },
            // 回调
            callbackFun(){
                console.log('callbackFun--this.uploadList',this.uploadList);
                let uploadList = this.forUploadImg(this.uploadList);
                this.$emit('callback',{
                    uploadList: uploadList,
                });
                //this.activityValidate.img_url = uploadList[0]||'';
                console.log('this.activityValidate', this.activityValidate);
            },
        },
        mounted() {       
            this.uploadList = this.$refs.upload.fileList;
        }
    }

</script>
<style lang='scss' scoped>
.upload-btn{
    width: 70px;height:70px;line-height: 70px;display: flex;align-items: center;justify-content: center;
}
.upload-list-box{
    display: flex;
}
.upload-list{
    display: inline-block;width: 70px;height: 70px;text-align: center;line-height: 70px;border: 1px solid transparent;
    border-radius: 4px;overflow: hidden;background: #fff;position: relative;box-shadow: 0 1px 1px rgba(0,0,0,.2);margin-right: 4px;
}
.upload-list img{
    width: 100%;height: 100%;display: block;
}
.upload-list-cover{
    display: none;position: absolute;top: 0;bottom: 0;left: 0;right: 0;background: rgba(0,0,0,.6);
}
.upload-list:hover .upload-list-cover{
    display: block;
}
.upload-list-cover i{
    color: #fff;font-size: 20px;cursor: pointer;margin: 0 2px;
}	
</style>

使用:

<uploadImage  v-if="pageShow" :maxLength="1" @callback="homePictureImages" :defaultList="home_picture" />



版权声明:本文为ys_dd原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。