gpt4 book ai didi

reactjs - 如何在reactjs中使用formData添加多张图片

转载 作者:行者123 更新时间:2023-12-04 14:21:35 24 4
gpt4 key购买 nike

我是 Reactjs 的新手。我正在使用 loopback-storage-connecter 来存储图像/文件。现在我的问题是使用 formData()

上传多个文件

我的代码

constructor(props){
super(props);
this.state = {
car_photo : [],
Car_Image : []
}
}
fileUploadCarImg = ()=> {
const fd = new FormData();
this.state.Car_Image.forEach((item , i) => {
fd.append('image2',this.state.Car_Image, this.state.Car_Image.name )
});

axios.post('http://localhost:3000/api/attachmentBanks/Car_Image/upload',fd , {
onUploadProgress : ProgressEvent => {
console.log('Upload Progress: ' + Math.round(ProgressEvent.loaded / ProgressEvent.total *100) + '%')
}
})
.then(res => {
this.setState({
car_photo: res.data.result.files.image2[0].name,

});

});
}

fileSelectedCarImg = event =>{
console.log(Array.from(event.target))
this.setState({
Car_Image: Array.from(event.target.files[0])
})

}

我的输入框是

<FormGroup>
<span>Car Image</span>
<input style={{display :'none'}} type="file" onChange={this.fileSelectedCarImg} ref={fileInput3 => this.fileInput3 = fileInput3 } required multiple />
<Button onClick={()=>this.fileInput3.click()} ><Icon type="upload" />Choose Image
</Button> &nbsp;
<Button onClick={this.fileUploadCarImg}> upload </Button>
</FormGroup>

在使用此代码时 Upload Progress: 100% 打印在控制台中,但文件没有进入文件夹。请任何人帮助

最佳答案

我找到了工作代码

fileSelectedCarImg = event =>{
const file = Array.from(event.target.files);
this.setState({ file })
}

fileUploadCarImg =()=>{
for (let index = 0; index < this.state.file.length; index++) {
const element = this.state.file[index];
const fd = new FormData();
fd.append('image2',element,element.name )
axios.post('http://localhost:3000/api/attachmentBanks/Car_Image/upload',fd , {
onUploadProgress : ProgressEvent => {
console.log('Upload Progress: ' + Math.round(ProgressEvent.loaded / ProgressEvent.total *100) + '%')
}
})
.then(res => {
this.setState({
car_photo: res.data.result.files.image2[0].name,
});

});

}
}

关于reactjs - 如何在reactjs中使用formData添加多张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54235218/

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