gpt4 book ai didi

reactjs - 使用 reactjs 上传多个文件

转载 作者:行者123 更新时间:2023-12-03 13:44:55 24 4
gpt4 key购买 nike

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

我的 react 代码。

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

最佳答案

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

for (let i = 0; i < files.length; i++) {
formData.append(`images[${i}]`, files[i])
}
在服务器端,您将从请求对象/变量的“图像”键中获取所有图像

关于reactjs - 使用 reactjs 上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59451364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com