使用axios和JavaScript上传图像并在表格中指示响应

Bha*_*iya 6 javascript css reactjs axios

在此输入图像描述我想要将10个图像一起上传axios并向后端发送请求以使用这10个文件进行一些计算,在计算之后会有响应{imagename: true}{imagename: false}从后端接收响应我想在前端列出那10个图像并指示计算是真还是假.

这是我尝试的但是在得到回复并且无法显示真实或错误状态后我被卡住了.

import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { Grid, Row, Col } from 'react-flexbox-grid';
import axios, { post } from 'axios';
import compose from 'recompose/compose';
import { withStyles } from '@material-ui/core/styles';
import Styles from '../styles';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';

import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import { Scrollbars } from 'react-custom-scrollbars';

import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';




class ImageUploader extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null,
      user_name:this.props.username,
      checkboxcolor:false,
      detailsResoponse:[],
      responseList:[],
      imageList:[],
      uploadResponse:'priya',
      a:[],
      loaded: 0
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.handelFile = this.handelFile.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  onFormSubmit(){
    this.setState({
        responseList:[]
    })
    var files=this.state.file
    for(var i in files){
        this.fileUpload(files[i])
        .then((response)=>{
            // console.log(response.data);
        })
    }
  }


handelFile(e) {
    if(e.target.files.length == 10) {
        var self=this
        self.setState({
            imgList:[],
            file:e.target.files,
        })
        for(var i in e.target.files){
            if(i != 'length' && i != 'item'){
                if(e.target.files[i].type.split('/')[0] == 'image'){
                   self.state.imageList.push(e.target.files[i])
                }
            }
        }       
    }
    else{
        alert('Please upload 10 images')
    }     
}

urlBlob(id,file){
    var reader = new FileReader();
    reader.onload = function (e) {

        var image=document.getElementById(id)
        image.src=e.target.result

    }
    reader.readAsDataURL(file); 
}


fileUpload(file){
    const url = 'http://abc';
    const formData = new FormData();
    formData.append('image',file)

    const config = {
        headers: {
            'content-type': 'multipart/form-data',
            'Access-Control-Allow-Origin':'*'
        }
    }
    return  axios.post(url,formData,config)
    .then(res => {

        var jsondata=JSON.stringify(res.data)
        JSON.parse(jsondata, (key, value) => {
            // if (value == true) {
                // this.state.a.push(key)
                var arrayList= this.state.responseList
                arrayList.push(res.data)
                    this.setState({
                        responseList:arrayList,
                        // checkboxcolor:true
                     })
            // }
          });
        }
     )
    .catch(function (error) {
      alert(error)
  });
}


  render(){
    const { classes } = this.props;
    console.log(this.state.a)
    console.log(this.state.imageList,"yep")
    // console.log(this.state.responseList,"responseList")
    return (
      <div>
          <Grid>
                <Row>
                    <Col sm={12} md={12} lg={12}>
                        <AppBar position="static" color="inherit" className={classes.app}>
                            <Toolbar>
                            <Typography variant="title" color="inherit">
                              Upload Image
                            </Typography>
                            </Toolbar>
                        </AppBar>
                    </Col>
                </Row>


                <Row>
                    <Col sm={12} md={12} lg={12}>
                       <Paper elevation={3} style={{padding:20,height:25,marginBottom:20}}> 
                            <input 
                                  id="fileItem"
                                   type="file" onChange={this.handelFile}
                                   multiple
                            />
                            <Button color="primary" onClick={this.onFormSubmit}> Upload</Button>
                       </Paper>
                    </Col>
                </Row>

                <Row>
                    <Col sm={12} md={12} lg={12}>
                            <Table style={{width:'80%',position:'relative',left:'8%',border:'2px solid lightgrey',marginTop:'3%'}}>
                            <TableHead> 
                                <TableRow >
                                    <TableCell className={classes.phPadding}> Checkbox </TableCell>
                                    <TableCell className={classes.phPadding}> Image </TableCell>
                                    <TableCell className={classes.phPadding}> Name </TableCell>
                                    <TableCell className={classes.phPadding}> Username</TableCell>
                                    <TableCell style={{width:'10%'}}></TableCell>
                                </TableRow>
                            </TableHead>
                        </Table>
                        <Scrollbars style={{height: 328}}>

                        {this.state.imageList.map((item,key)=> (
                            <Table style={{width:'80%',position:'relative',left:'8%',border:'2px solid lightgrey',borderTop:'0px'}}>
                                <TableBody>
                                        <TableRow key={key}>
                                            <TableCell className={classes.phPadding}>

                                                {this.state.checkboxcolor ? 

                                                    <FormControlLabel
                                                        control={
                                                            <Checkbox
                                                                checked={this.state.checkboxcolor}
                                                            />
                                                        }
                                                />
                                            :
                                                null

                                             }

                                            </TableCell>
                                            <TableCell className={classes.phPadding}>
                                                <img id={"image"+key} src={this.urlBlob("image"+key,item)} height="90" width="90" /> 
                                            </TableCell>
                                            <TableCell className={classes.phPadding}>{item.name}</TableCell>
                                            <TableCell className={classes.phPadding}>{/* {this.state.user_name} */}user_name</TableCell>

                                            <TableCell> 

                                            </TableCell>

                                     </TableRow>
                                </TableBody>
                            </Table>
                        ))}
                         </Scrollbars>
                    </Col>
                </Row>
            </Grid>
      </div>
   )
  }
}

export default compose(withStyles(Styles))(ImageUploader);
Run Code Online (Sandbox Code Playgroud)

console.log(res.data) 响应

console.log(res.data)响应

Hem*_*ari 2

编辑:要解决以下问题,您需要在handleFile函数下添加event.persist() 。

未捕获的类型错误:无法读取 null 的属性“文件”

我使用 ES6 更新了所有代码。

我注意到您代码中的一些不好的做法并纠正了它们

  1. 将元素推送到状态数组的方式不正确,而是使用
    先前的状态来处理反应状态下的数组。
  2. 停止使用 var
    而是使用 let 和 const
  3. 停止将 this 分配给 self 而是使用箭头函数,这样您就不需要手动绑定,也不需要依赖局部变量,即 self

我已经更正了你的代码。此代码将根据您的需要显示图像响应

import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { Grid, Row, Col } from 'react-flexbox-grid';
import axios, { post } from 'axios';
import compose from 'recompose/compose';
import { withStyles } from '@material-ui/core/styles';
import Styles from '../styles';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import { Scrollbars } from 'react-custom-scrollbars';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';

class ImageUploader extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null,
      user_name:this.props.username,
      detailsResoponse:[],
      responseList:[],
      imageList:[],
      uploadResponse:'priya',
      a:[],
      loaded: 0
    }
  }

  onFormSubmit = () => {
    this.setState({
        responseList:[]
    })
    let files = this.state.file;
    for(var i in files){
      this.fileUpload(files[i]);
    }
  }

handelFile = e => {
    e.persist();
if(e.target.files.length == 10) {
    this.setState({
        imgList:[],
        file:e.target.files,
    })
   for(let i=0; i < e.target.files.length; i++){
      if(e.target.files[i].type.split('/')[0] == 'image'){
        this.setState(prevState => ({
          imageList: [...prevState.imageList, e.target.files[i]]
        }));
      }
    }       
}
else{
    alert('Please upload 10 images')
}     
}

urlBlob = (id,file) => {
    let reader = new FileReader();
    reader.onload = e => {
        let image = document.getElementById(id);
        image.src = e.target.result;
    }
    reader.readAsDataURL(file); 
}


fileUpload = file => {
    const url = 'http://172.16.92.21:9999';
    const formData = new FormData();
    formData.append('image',file)
    formData.append('uname','150180')
    const config = {
        headers: {
            'content-type': 'multipart/form-data',
            'Access-Control-Allow-Origin':'*'
        }
    }
    axios.post(url, formData, config)
    .then(res => {
        this.setState(prevState => ({
            responseList: [...prevState.responseList, res.data]
          }));
        });
    .catch(error => {
      alert(error)
  });
}


  render(){
    const { classes } = this.props;
    const { responseList } = this.props;
    console.log(this.state.a)
    console.log(this.state.imageList,"yep")
    // console.log(this.state.responseList,"responseList")
    const imagesResponse = responseList && responseList.map((image, index) => {
      return <li className="list-group-item">{image}</li>
    });
    return (
      <div>
          <Grid>
              <Row>
                <Col>
                  <ul className="list-group">
                    {imagesResponse}
                  </ul>
                </Col>
              </Row>
                <Row>
                    <Col sm={12} md={12} lg={12}>
                        <AppBar position="static" color="inherit" className={classes.app}>
                            <Toolbar>
                            <Typography variant="title" color="inherit">
                              Upload Image For Surveillance
                            </Typography>
                            </Toolbar>
                        </AppBar>
                    </Col>
                </Row>


                <Row>
                    <Col sm={12} md={12} lg={12}>
                       <Paper elevation={3} style={{padding:20,height:25,marginBottom:20}}> 
                            <input 
                                  id="fileItem"
                                   type="file" onChange={this.handelFile}
                                   multiple
                            />
                            <Button color="primary" onClick={this.onFormSubmit}> Upload</Button>
                       </Paper>
                    </Col>
                </Row>

                <Row>
                    <Col sm={12} md={12} lg={12}>
                            <Table style={{width:'80%',position:'relative',left:'8%',border:'2px solid lightgrey',marginTop:'3%'}}>
                            <TableHead> 
                                <TableRow >
                                    <TableCell className={classes.phPadding}> Checkbox </TableCell>
                                    <TableCell className={classes.phPadding}> Image </TableCell>
                                    <TableCell className={classes.phPadding}> Name </TableCell>
                                    <TableCell className={classes.phPadding}> Username</TableCell>
                                    <TableCell style={{width:'10%'}}></TableCell>
                                </TableRow>
                            </TableHead>
                        </Table>
                        <Scrollbars style={{height: 328}}>

                        {this.state.imageList && this.state.imageList.map((item,key)=> (
                            <Table style={{width:'80%',position:'relative',left:'8%',border:'2px solid lightgrey',borderTop:'0px'}}>
                                <TableBody>
                                        <TableRow key={key}>
                                            <TableCell className={classes.phPadding}>

                                                {responseList ? responseList.map((image, index) => {
                                                  return (<FormControlLabel key={index}
                                                        control={
                                                            <Checkbox
                                                                checked={item.name == image.name && image.flag ? true : false }
                                                            />
                                                        }
                                                    />)
                                                }): <FormControlLabel
                                                        control={
                                                            <Checkbox
                                                                checked={false}
                                                            />
                                                        }
                                                    />
                                               }



                                            </TableCell>
                                            <TableCell className={classes.phPadding}>
                                                <img id={"image"+key} src={this.urlBlob("image"+key,item)} height="90" width="90" /> 
                                            </TableCell>
                                            <TableCell className={classes.phPadding}>{item.name}</TableCell>
                                            <TableCell className={classes.phPadding}>{/* {this.state.user_name} */}user_name</TableCell>

                                            <TableCell> 

                                            </TableCell>

                                     </TableRow>
                                </TableBody>
                            </Table>
                        ))}
                         </Scrollbars>
                    </Col>
                </Row>
            </Grid>
      </div>
   )
  }
}

export default compose(withStyles(Styles))(ImageUploader);
Run Code Online (Sandbox Code Playgroud)

请从您这边进行测试并告诉我