Element-ui upload组件 上传限制文件类型、文件大小、手动上传

1.
template :   
            
<el-upload
                        ref="upload"
                        class="upload-demo"
                        :before-remove="beforeRemove"
                        :file-list="fileList"
                         action
                        :on-change="onChange"
                        accept=".pdf, .doc, .docx"
                        :auto-upload="false"
                        :on-success="upSuccess"
                        :on-error="upError"
                    >
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传pdf、doc、docx文件,且不超过10MB</div>
</el-upload>
 
 

2.

data:
 fileList: [],
upFile: new FormData(),
 
 

3.

methods:
        onChange(file, fileList) {
            this.fileList = fileList
            const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
            const whiteList = ['pdf', 'doc', 'docx']
            const isSuffix = whiteList.indexOf(fileSuffix.toLowerCase()) === -1
            const isLt10M = file.size / 1024 / 1024 > 10
            console.log('this.fileList:', this.fileList)
            if (isSuffix) {
                this.$message.error('上传文件只能是 pdf、doc、docx格式')
                const currIdx = this.fileList.indexOf(file)
                this.fileList.splice(currIdx, 1)
                return
            }
            if (isLt10M) {
                this.$message.error('上传文件大小不能超过 10MB')
                const currIdx = this.fileList.indexOf(file)
                this.fileList.splice(currIdx, 1)
                return
            }
        },
 
        //上传文件接口 根据自己业务修改 ,记得封装axios的时候 修改headers。
  //注意:发送post请求的时候字符串 “null”而不是 null ,原因:content-type走的 form-data,所以是字符串“null”,而 null 这个概念是 json 的,所以你走 application/json 才可以。特别是日期组件如果没选日期传递的可能是字符串null,注意判断!!!
// 附件上传
// export function sendFile(data) {
//     return req.post('/lawsAndRegulations/upload', data, {
//         headers: {
//             'Content-Type': 'multipart/form-data',
//         },
//     })
// }
 
        submitFile() {
           
            this.fileList.forEach((val, index) => {
                this.upFile.append('file', val.raw)
            })           
   sendFile(this.upFile)
                .then((res) => {
                    this.lawForm.fileCode = res.data.data
                    this.upFile = new FormData()
                })
                .catch((err) => {
                    this.upFile = new FormData()
                    console.log(err)
                })
        },
        // 上传成功
        upSuccess(e) {
            this.$message.success('上传成功')
        },
        // 上传失败
        upError(e) {
            this.$message.error('上传失败', 'error')
        },
posted @ 2022-07-22 15:45  赵辉Coder  阅读(13948)  评论(0编辑  收藏  举报