reactjs - 使用 reactjs 上传多个文件
问题描述
我是新手reactjs
,我正在尝试上传多个文件上传。我可以将状态组件中的文件存储为 array 。但是当我将数据传递给 axios post 方法时,它给我的文件列表为[object FileList]
. 而且我无法遍历这些文件来存储 . 甚至我尝试了多种方法来上传多个文件,例如“react-Dropzone”。但没有帮助。
我的反应代码。
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])
}
在服务器端,您将从请求对象/变量的“图像”键中获取所有图像
推荐阅读
- java - 如何获取网页上元素的html代码
- html - CSS 缩放不重叠
- python - Pandas 滚动两个数据帧的累积总和
- javascript - 当使用 onclick 按钮创建文本时,使用 onmouseover 突出显示文本
- php - 如何从 woocommerce 产品对象中找到相关的 learndash 课程 ID?
- java - 条目名称“javax/annotation/CheckReturnValue.java”冲突生成调试 apk
- ios - 我如何请求参数 Alamofire 表单数据?
- jquery - 为什么 jQuery.validator.unobtrusive.adapters.addBool() 没有按预期工作?
- php - 将一串数字表示为星期几
- c# - 有没有办法让 Dns.GetHostEntry() 在 C Sharp 中强制使用 TCP 而不是 UDP?