【问题标题】:Multiple file upload with reactjs使用 reactjs 上传多个文件
【发布时间】:2020-04-14 12:12:44
【问题描述】:

我是reactjs 的新手,我正在尝试上传多个文件。我可以将状态组件中的文件存储为 array 。但是当我将数据传递给 axios post 方法时,它给我的文件列表为 [object FileList] 。而且我无法遍历这些文件来存储 .甚至我尝试了多种方法来上传多个文件,例如“react-Dropzone”。但没有帮助。

我的反应代码。

handleChange(event) {
  this.setState({ file: event.target.files })
}

async handleSubmit(e) {
  e.preventDefault()
  let res = await this.uploadFile(this.state.file);
}

async uploadFile(File){
  const formData = new FormData();

  formData.append('image', File)
  axios.post(UPLOAD_ENDPOINT, formData, {
    headers: {
      'content-type': 'multipart/form-data'
    }
  }).then(response => {
    console.log(response.data)
  });
}

render() {
  return (
    <form onSubmit={this.handleSubmit}>
      <input type="file" id="file" multiple name="file" onChange={this.handleChange} />
      <button type="submit" className="btn btn-info"> Update File </button>
    </form>
  )
}

【问题讨论】:

    标签: reactjs react-native react-router multiple-file-upload


    【解决方案1】:

    event.target.files
    

    将为您提供一个文件列表,并将其附加到表单数据中,请使用以下代码。

    const files = event.target.files;
    
    for (let i = 0; i < files.length; i++) {
        formData.append(`images[${i}]`, files[i])
    }
    

    在服务器端,您将从请求对象/变量的 'images' 键中获取所有图像

    【讨论】:

    • 漂亮而简单。 files 可能是 const
    【解决方案2】:
    for (let i = 0; i < files.length; i++) { 
        formdata.append(`images[${i}]`, {
                        uri: pathOfFile,
                        name: fileName.jpg,
                        type: mimeType(eg. "image/jpeg")
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      相关资源
      最近更新 更多