如何在reactjs中使用formData添加多个图像 [英] How to add multiple images by using formData in reactjs

查看:612
本文介绍了如何在reactjs中使用formData添加多个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Reactjs的新手.我正在使用回送存储连接器来存储图像/文件.现在我的问题是使用formData()

Im new to Reactjs. I am using loopback-storage-connecter to store images/files. now my problem is to upload more than one file by using 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%代码时

,但文件并没有刺入文件夹. 请任何人帮助

while using this code Upload Progress: 100% printed in console, but file didn't sore into the folder. Please anyone help

推荐答案

我找到了工作代码

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中使用formData添加多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆