reactjs 形式的多文件上传器

IT技术 reactjs file-upload redux
2021-05-09 12:36:40

我在数据库中有一个项目列表,我想将它呈现在表格中,并将为每个添加 input type=file 以上传每个项目的文件单击句柄我想发送项目名称来处理函数,但我不能让它更清楚我想发送值 item.documentname 到 file1MadChangedHandler 函数,每次我点击

   {this.props.Organizations.listDocs 
    ? 
    <div>
       { this.props.Organizations.listDocs.map(function (item, index) {
          return(
                <tr key={item.documentName}>
                    {item.documentName}
                        <td>
                        <td>
                            <input component="input"
                                type="file"
                                id="{item.documentName}"
                                onChange={(event,item)=> { 
                                    this.file1MadChangedHandler(event,item) }}
                                // onChange={this.file1MadChangedHandler}
                                ref={fileInput => ref.fileInput = fileInput}
                                style={{ display: "None" }}
                            />
                            <button onClick={(item) => this.fileInput.click(item.documentName)}>Pick File</button>             
                        </td>
                </tr>
            )

        })
                }
    </div> 
    : 
    ""
}
2个回答

fileHandler = (event) => {
  if(event.target.value !== ""){
    event.preventDefault();
    this.form.validateFields(event.target.name);

    const fileObject = event.target.id;  
    const name = event.target.files[0].name;
    const size = ((event.target.files[0].size)/1000000).toFixed(2);
    let img = [...this.state.img];

    img.push({inptid: fileObject,
      name: name,
      size: size});

    const fetchImage = img.map(e => e['inptid'])
    .map((e, i, final) => final.lastIndexOf(e) === i && i)
    .filter(e => img[e]).map(e => img[e]);

    this.setState({ img: fetchImage});

  }else{
    return false;
  }
}

注意我们的渲染部分和表单是通过循环动态出现的,适用于您的情况可能会有所不同

<input
  type="file"
  className="form-control none"
  ref={formfields.title}
  name={formfields.title}
  id={formfields._id}
  key={formfields._id}
  index={formindex}
  onChange={this.fileHandler}
  required
/>

{
  img.filter(data => data.inptid === formfields._id)
  .map((data,index) =>{
    return(
      (data.inptid === formfields._id)
      ?
      <p>{data.name}   - <i><b>{data.size} MB </b></i></p>
      :
      ''
    )
  }) 
}

使用来自您的repl.it/repls/MutedFunnyBlog代码的输入

要获取上传项目的文件名,您需要稍微更改您的数据,如下所示:

data: [
      { id: 1, name: "Copy of Applicant's Identification Card / Passport", "file": "" },
      { id: 2, name: "Copy of Business Registration Certificate (eg. SSM)", "file": "" },
      { id: 3, name: "Copy of Business Registration File 1", "file": "" },
      { id: 4, name: "Copy of Business Registration File 2", "file": "" }
    ]  //added file

然后渲染每一行,如下所示:

   data.map((item, index) => {
    return(
      <tr key={`${this.state.inputkey}${item.id}`}>
        <td width="100">{item.id}</td>
        <td width="300">{item.name}</td>
        <td width="200">{item.file}</td> /* your third column */
        <td>
        <input 
          key={this.state.inputkey} /*unique key */
          type="file" 
          id={item.id} /*unique id cus every row should have unique input file type*/
          className="inputfile"
          onInput ={(e) => this.handleChange(e,item.id)} 
          data-name={item.id} />
        <label htmlFor ={item.id} > /* unique id for file upload*/
          <figure>
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" viewBox="0 0 20 17"><path d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z"/>
            </svg>
          </figure> 
        </label>           
        </td>
      </tr>
    );
});

并在 handleChange 事件中:

 handleChange(event, i) {
      const newData = this.state.data.map(item => ({...item}) ); //copy state.data to new data
      newData.map(item => item.file = i === item.id ? event.target.files[0].name: item.file);  //set file based on uploaded file in each row
      this.setState({ 
          data: newData, 
          inputkey: Math.random().toString(36) //set new unique key here
        }, () =>  console.log(this.state.data));
  }

演示,希望它可以解决您的问题。

如果需要使用按钮代替标签,则必须使按钮单击事件触发 input type="file" 事件。 按钮演示

<button onClick={e => this.enableInputFile(e, item.id)}>
    Upload
</button>

  enableInputFile(e, id) {
    document.getElementById(id).click();
  }

注意:您不能将 for/htmlFor 添加到按钮,因为它不是可标记的元素,请 在此处检查