【vue】使用 el-upload+axis实现手动多文件上传的代码实现

代码实现

以下是一个使用Element UI的el-upload和Axios实现手动多文件上传的示例代码:

<template>
  <div>
    <el-upload
      ref="upload"
      action="/upload"
      :auto-upload="false"
      :on-change="handleUploadChange"
      :file-list="fileList"
      multiple
    >
      <el-button size="small" type="primary">选择文件</el-button>
    </el-upload>
    <el-button size="small" type="success" @click="uploadFiles">上传文件</el-button>
  </div>
</template>

<script>
import axios from 'axios'

export default {
      
      
  data() {
      
      
    return {
      
      
      fileList: []
    }
  },
  methods: {
      
      
    handleUploadChange(file, fileList) {
      
      
      this.fileList = fileList
    },
    uploadFiles() {
      
      
      const formData = new FormData()
      for (let i = 0; i < this.fileList.length; i++) {
      
      
        formData.append('file', this.fileList[i].raw)
      }
      axios.post('/upload', formData)
        .then(response => {
      
      
          console.log(response.data)
        })
        .catch(error => {
      
      
          console.error(error)
        })
    }
  }
}
</script>

说明

在上面的代码中,我们首先使用el-upload组件创建了一个文件上传输入框,并设置multiple属性以允许用户选择多个文件。接着,在按钮上添加了一个@click事件处理程序,用于在用户选择文件后手动触发上传操作。

在uploadFiles()方法中,我们首先创建了一个FormData对象,并将所有要上传的文件添加到该对象中。然后,我们使用Axios发送一个POST请求,将FormData对象作为第二个参数传递给该方法。当服务器返回响应时,我们可以在.then回调函数中访问响应数据。如果发生错误,则可以在.catch回调函数中访问错误信息。

需要注意的是,在上传文件之前,我们必须先将文件添加到FormData对象中,这里使用了this.fileList[i].raw来获取每个要上传的文件的原始数据。另外,由于我们将自动上传(auto-upload)属性设置为false,因此需要通过handleUploadChange()方法将选择的文件列表保存到组件状态中(fileList)。

猜你喜欢

转载自blog.csdn.net/qq_38428623/article/details/129985648