【问题标题】:How to add multiple images by using formData in reactjsreactjs中如何使用formData添加多张图片
【发布时间】:2019-01-19 04:00:05
【问题描述】:

我是 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% 打印在控制台中时,但文件没有进入文件夹。 请大家帮忙

【问题讨论】:

    标签: reactjs form-data


    【解决方案1】:

    我找到了工作代码

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

    【讨论】:

      猜你喜欢
      • 2021-03-27
      • 2020-08-18
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      相关资源
      最近更新 更多