vue文件上传

132 阅读1分钟
<el-upload :action="actionUrl" :data="ossData" :headers="headers" :before-upload="beforeUpload" :on-success="onSuccess" :on-error="onError" :on-change="onChange"  :on-exceed="onExceed" :file-list="fileList" :limit="limit" accept=".xls,.xlsx">
    //可以通过加这个input进行文件校验
    <el-input size="mini" v-model="fileName" v-show="false">
    </el-input>
</el-upload>

<script> 
export default {
data() { 
    return {
            actionUrl:'http:****',//上传地址,必填
            ossData:{},//上传时附带给后台的参数
            headers:{},//设置上传的请求头部
            fileList:[],//上传的文件列表
            limit:1,//上传个数
        }
    },
    methods: {
            //上传文件之前的钩子
         beforeUpload(file) {
         let suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
         if (suffix != 'xls') {
                this.$notify.warning({ message: "请上传指定的文件格式!", duration: 2000 })
                return false;
            }
                this.ossData.id = 7;//给后台除了文件多传一个id
        },
        //文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
         onChange(file, fileList) {
            // 文件20M限制
            if (file.size > 1024 * 1024 * 20) {
                this.$notify.warning({ message: "请上传不超过 20M 大小的文件",})
                return false;
            }
             if (fileList.length > 1) {
                fileList = [fileList[1]]
            }
            this.fileList = fileList
            this.$refs.upload.submit();
        },
        //文件上传成功时的钩子
        onSuccess(resp, file, fileList) {
          
        },
        文件上传失败时的钩子
        onError(err, file, fileList) {
           
        },
        //文件超出个数限制时的钩子
         onExceed(files, fileList) {
            this.$notify.error({ title: `请不要超过1个文件` });
        },
    }
} 
</script>