Search code examples
reactjsform-data

How to add multiple images by using formData in reactjs


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

my code

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

    }

my input field is

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

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


Solution

  • I found the working code

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