vue之Element 上传组件 el-upload

1.第一种自动上传,需提前写好接口地址和请求参数


<template>
    <div>
      <el-form>
        <el-upload
          :show-file-list="false"
          :limit="1"
          :action= actionUp
          :before-upload="beforeFile"
          :on-success="successFile"
          :data="reportData"
          :file-list="fileList">
          <el-button size="small" type="primary">上传</el-button>
        </el-upload>
      </el-form>
    </div>
</template>

<script>
    export default {
        data() {
            return {
              actionUp:'http://XXXXX',//接口地址
              fileList:[],
              reportData:{  //请求带的参数
                mold:4,
                name:'123111'
              }
            }
        },
        methods: {
          /**
           * 文件上传之前 判断格式
           * */
          beforeFile(file){
            let name = file.name
            let type = name.substring(name.lastIndexOf('.')+1)
            if (type !== 'docx') {
              this.$message('请上传word文件格式');
              return false
            }
          },
          /**
           *文件上传成功时的钩子
           * */
          successFile(file){
            this.$message({
              message: '上传成功',
              type: 'success',
              duration:1000
            })
          },

        }
    }
</script>
成功Network:
接口

1.第二种使用http-request ,覆盖默认的上传行为,可以自定义上传的实现。

<template>
    <div>
      <el-form>
        <el-upload
          :show-file-list="false"
          :limit="1"
          :action= actionUp
          :before-upload="beforeFile"
          :http-request="fileRequest"
          :file-list="fileList">
          <el-button size="small" type="primary">上传</el-button>
        </el-upload>
      </el-form>
    </div>
</template>

<script>
    export default {
        data() {
            return {
              actionUp:'aaaa',
              fileList:[],
            }
        },
        methods: {
          /**
           * 文件上传之前 判断格式
           * */
          beforeFile(file){
            let name = file.name
            let type = name.substring(name.lastIndexOf('.')+1)
            if (type !== 'docx') {
              this.$message('请上传word文件格式');
              return false
            }
          },
          fileRequest(item) {
            let uploadData = new FormData()
            uploadData.append('file',item.file)
            this.$axios.post('http:/XXXXX',uploadData
            )
              .then(res =>{
              //  成功
                console.log('8888')
              })
          }
        }
    }
</script>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。