Multiple file upload with reactjs

自闭症网瘾萝莉.ら 提交于 2020-08-07 05:17:41

问题


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.

My react Code .

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

回答1:


The

event.target.files

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

let files = event.target.files;

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

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




回答2:


for (let i = 0; i < files.length; i++) { 
    formdata.append(`images[${i}]`, {
                    uri: pathOfFile,
                    name: fileName.jpg,
                    type: mimeType(eg. "image/jpeg")
    });
}


来源:https://stackoverflow.com/questions/59451364/multiple-file-upload-with-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!