主机百科
测评与优惠

Element ui中upload组件一次请求批量上传

Element ui是由饿了么团队推出的基于vue的前端库,功能非常强大,其中的upload组件可以轻松的实现前端通过点击或者拖拽上传文件。不过upload组件默认的批量上传却是逐项上传,也就是你一次批量选择5个文件,那么会发送5次请求来分别上传这5个文件。

那么Element ui中upload组件怎么实现一次请求批量上传呢?这就需要通过自定义http-request来覆盖默认的上传行为,实现自定义上传,具体代码如下:

1
  <template>    <d2–container>  <el–upload     class="upload–demo"     ref="upload"      action=""      :http–request="customUpload"      :before–upload="beforeFileUpload"     :on–preview="handlePreview"     :on–remove="handleRemove"      :on–success="handleSuccess"     :file–list="fileList"     :auto–upload="false"      accept=".dbf"      multiple>     <el–button slot="trigger" size="small" type="primary">选取文件</el–button>     <el–button style="margin–left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el–button>     <!—div slot="tip" class="el–upload__tip">只能上传jpg/png文件,且不超过500kb</div>—>  </el–upload>    </d2–container>  </template>  <script>    export default {      data() {        return {          fileList: [],          fileData: new FormData()        };      },      methods: {        submitUpload() {          this.$refs.upload.submit();          fileUpload(this.fileData).then(response => {            })        },        beforeFileUpload(file){          let extension=file.name.substring(file.name.lastIndexOf('.')+1);          const isDbf = extension === "dbf";          const isLt10M = file.size / 1024 / 1024 < 10          if (!isDbf) {            this.$message.error('上传的数据文件只能是dbf格式!');          }          if (!isLt10M) {            this.$message.error('上传的单个数据文件大小不能超过10MB!');          }          return isDbf && isLt10M;        },               handleRemove(file, fileList) {        },        handlePreview(file) {        },        handleSuccess(response,file, fileList) {          this.$message.success('上传成功')        },        customUpload(file) {          this.fileData.append('files[]', file.file)          return false        }      }    }    //引入axios    import request from '@/plugin/axios'    export function fileUpload(file) {      return request({        method: 'post',        url: 'http://localhost/api/import',        headers: {'Content-Type':'multipart/form-data'},        data: file      })    }  </script>

代码说明:

1.配置自定义的http-request函数:

1
  :http–request="customUpload"

2.在data中添加一项参数:fileData,类型是FormData:

1
  fileData: new FormData()

3.实现customUpload方法,将上传文件信息拼接到fileData中。

1
  customUpload(file) {    this.fileData.append('files[]', file.file)    return false  }

4.定义axios异步上传方法:

1
  export function fileUpload(file) {    return request({     method: 'post',     url: 'http://localhost/api/import',     headers: {'Content-Type':'multipart/form-data'},     data: file    })    }

5.在submitUpload中调用4中定义的上传方法:

1
  submitUpload() {    this.$refs.upload.submit();    fileUpload(this.fileData).then(response => {    //console.log(response)    })  },

未经允许不得转载:主机阁 » Element ui中upload组件一次请求批量上传

登录

找回密码

注册