vue2+element ui 上传文件

完全基于elementui组件封装的上传组件 ,后期继续优化

<template>
    <div>
        <el-upload
            class="upload-demo"
            :headers="headers"
            :data='uploadData'
            :action="action"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success='handleSuccess'
            :before-remove="beforeRemove"
            :before-upload='beforeUpload'
            :multiple='false'
            :limit="10"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传<span v-for="(v,i) in fileTypeList" :key="i">.{{v}}<i v-if="i+1 < fileTypeList.length"></i></span>等格式文件,最大10M</div>
            </el-upload>
        <el-dialog class="common-dialog" title="详情" v-if="preview" :visible.sync="preview" width="1000rem" append-to-body>
            <div>
                  <img style="width: 100%; height:800px;" :src="currentImg" alt="">
            </div>
        </el-dialog>  
    </div>

</template>
<script>
    import * as config from '@/common/env.json';
    export default {
        // list:文件列表 数组,fieldName 字段名, prefix 是 prefix对应的 参数名
        props:['List','fieldName','prefix'],
        data() {
            return {
                // 允许上传的文件类型
                fileTypeList:['png','jpg','jpeg','gif','slx','xlsx','doc','docx','pdf'],
                fileList:[],
                // 传给后端的参数
                uploadData:{},
                // 设置请求头
                headers:{
                    token:sessionStorage.getItem('token')
                },
                // 设置请求地址
                action: (process.env.NODE_ENV == 'development'? config.serviceUrlDev: config.serviceUrlProd)+'control/file/uploadFile', //action就写成上传文件的接口我这里是动态设置请求地址
                preview: false,
                currentImg:null,
                fileUrl:null,
            }
        },
        created() {
            this.fileUrl = process.env.NODE_ENV == 'development' ? config.serviceUrlDev + config.fileService : config.serviceUrlProd + config.fileService;
            this.uploadData={ prefix:this.prefix}
        },
        watch:{
        //深度监听 不知道这步起效果没有
            List:{
                  handler(n, o){
                    if(n){
                        this.fileList=n;
                    }
                  },
                  immediate: false
            }
        },
        methods: {
        //拼接图片完整地址
            funPicture(item) {
                return this.fileUrl + item;
            },
            //删除文件方法
            handleRemove(file, fileList) {
                let data=[];
                for(let i of  fileList){
                    data.push(i.url)
                }
                let  dataStr=(data && data.length !=0) ? data.join(','):'';
                this.$emit('uploadDone',dataStr,this.fieldName)
            },
            //点击文件列表的文件触发的事件
            handlePreview(file) {
                console.log(file)
                if( this.$formatFileType(file.name.substring(file.name.lastIndexOf('.') + 1))=='pic'){
                    this.currentImg=this.funPicture(file.url);
                    this.preview=true;
                }else{
                    this.downLoad(file)
                }
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 10 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
            },
            beforeRemove(file, fileList) {
                // return this.$confirm(`确定移除 ${ file.name }?`);
            },
            //上传之前做文件类型和大小判断
            beforeUpload(file){
                let arr = file.name.split('.');
                let istrue = this.fileTypeList.indexOf(arr[arr.length - 1]);
                if (istrue == -1) {
                    this.$message.warning('错误!文件格式不支持')
                    return false
                }
                if (file.size > 10485760) {
                    this.$message.warning('错误!文件大小不能超过10M')
                    return false
                }
                
            },
            //完成上传的事件 做后续操作
            handleSuccess(response, file, fileList){
                if(response.success){
                    let data=[];
                    for(let i of this.fileList){
                        data.push(i.url);
                    }
                    data.push(response.data);
                    let  dataStr=data.join(',')
                    this.$emit('uploadDone',dataStr,this.fieldName)
                }
            },
            //下载文件
            downLoad(file) {
                let fileDto = {
                    prefix: 'file/'+file.prefix,
                    fileName: file.name
                }
                this.$api.apiFileDownloadFile(fileDto).then((data) => {
                    const url = window.URL.createObjectURL(new Blob([data], { type: "application/pdf" }))
                    const link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = url
                    link.setAttribute('download', file.name)
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                })
            },
        }
    }
</script>

父组件使用
1、引入组件

                                <IDCardUploader   @uploadDone='uploadDone'   :list='formData.cardUpload'  fieldName='cardUpload'   prefix='cardUpload'  ></IDCardUploader>


 uploadDone(val,fileName){
                // console.log(val,fileName)
                this.formData[fileName]=val;
                console.log(this.formData)
            },

你可能感兴趣的:(vue.js,前端)