问题
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