How to add multiple images by using formData in reactjs

情到浓时终转凉″ 提交于 2019-12-11 16:07:57

问题


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


回答1:


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

            });

        }
    }


来源:https://stackoverflow.com/questions/54235218/how-to-add-multiple-images-by-using-formdata-in-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!