如何从 Vue 中的 ElementUI "el-upload" 获取文件名?

How to get file name from ElementUI "el-upload" in Vue?

我想获取上传的文件名,以便在 POST 请求的 :action URL 中使用它。我假设这需要在 :before-upload 期间发生,或者可以在没有方法的情况下检索它吗?

文档参考:https://element.eleme.io/#/en-US/component/upload#upload

<el-upload
  class="upload-demo"
  drag
  :action="url+filename+query"
  :on-error="handleUploadError"
  :on-success="handleUploadSuccess"
  :auto-upload="false"
  :before-upload="handleUploadbefore"
  :file-list="fileList"
  multiple>
  <i class="el-icon-upload"></i>
  <div class="el-upload__text">Drop file here or <em>click to upload</em></div>
  <div class="el-upload__tip" slot="tip">Only files with a size less than 3MB.</div>
</el-upload>

文件上传的目标URL基本上就是url+文件名+查询。

import { baseURL } from "@/utils/constants";

export default {
  name: "upload",
  data() {
    return {
      url: `${baseURL}/files/`,
      filename: null,
      query: `?override=true&auth=`
    }
  },
  methods: {
    handleUploadBefore() {

      return true;
    },    
    handleUploadError() {
      console.log("File upload failed.");
    },
    handleUploadSuccess() {
      console.log("File upload succeeded!");
    },
  }
};

before-upload的函数签名是function(file) {},其中file是一个File对象,它提供了一个nameprop

解决方案是更新您的回调以接收 file 参数:

handleUploadBefore(file) {
  console.log(file.name)
}

demo

您可以通过 $refs

使用 before-upload 访问它

this.$refs.upload.uploadFiles[0].name

demo