【问题标题】:How to insert custom properties to File object in react如何在反应中将自定义属性插入文件对象
【发布时间】:2021-05-15 10:45:53
【问题描述】:

我正在研究文件上传功能,当我选择多个文件或单个文件时我想要实现的目标是我想将自定义属性分配给每个File 对象自定义属性必须像percentage:0 到 File 对象。我很努力,但没有找到任何合适的解决方案来解决这个问题。有人可以帮我解决这个问题。

谢谢

代码

  addManualAttachments = (event) => {
    let files = event.target.files

    const fileList = Array.from(files)

    if (fileList.length > 10) {
      Swal.fire('Warning !', 'Maximum files upload limit is 10', 'warning')
      return false
    }

    for (let i = 0; i < fileList.length; i++) {
      if (this.validateFile(fileList[i])) {
        this.setState((prevState) => {
          return {
            ...prevState,
            selectedFiles: this.uniqueFiles([...prevState.selectedFiles, fileList[i]]),
          }
        })
      }
    }
  }

【问题讨论】:

    标签: javascript reactjs ecmascript-6 react-redux ecmascript-2016


    【解决方案1】:

    如果它是一个普通的 Javascript 对象,您可以在循环文件时将新的属性权限添加到文件中。此外,您可以使用 forEach 循环而不需要 for 循环:

    addManualAttachments = (event) => {
      const files = Array.from(event.target.files);
    
      if (files.length > 10) {
        Swal.fire('Warning !', 'Maximum files upload limit is 10', 'warning')
        return false
      }
    
      files.forEach((file) => {
        if(this.validateFile(file)) {
          file.percentage = 0; // <-- This will add the new property to the object reference stored for that file object.
          this.setState((prevState) => {
            return {
              ...prevState,
              selectedFiles: this.uniqueFiles([...prevState.selectedFiles, file]),
            }
          });
        }
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 2014-08-10
      • 2016-01-29
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 2017-08-16
      相关资源
      最近更新 更多