使用 reactjs 上传多个文件 [英] Multiple file upload with reactjs

查看:50
本文介绍了使用 reactjs 上传多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to reactjs and I'm trying to upload multiple file upload. I can able to store the files in state component as array . But When I'm passing the data to axios post method, it gives me the list of files as [object FileList] . And I couldn't able to traverse through that files to store . Even I tried multiple methods to upload multiple files like 'react-Dropzone`. But didn't help.

我的反应代码.

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>
  )
}

推荐答案

The

event.target.files

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

Will give you a file list, and to append it to form data use the following code.

const files = event.target.files;

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

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

On the server side you will get all the images from 'images' key of request object/variable

这篇关于使用 reactjs 上传多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆