Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload Image and indicating response in a table with axios and JavaScript

enter image description hereI want to upload 10 images together and send a axios request to backend to do some calculations with those 10 files , after calculations there will be response as {imagename: true} or {imagename: false} receiving the response from backend I want to list those 10 images on frontend with a indication that the calculation is true or false.

This is what I tried but I'm stuck after getting response and unable to show the true or false status.

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

console.log(res.data) response

console.log(res.data) response

like image 914
Bhart Supriya Avatar asked Sep 17 '18 09:09

Bhart Supriya


People also ask

How do I upload an image on Axios?

First, you create a local React state selectedFile using useState() hook to store the currently selected file, Second, the handleFileSelect event handler updates the selectedFile value using the setter function setSelectedFile and, Third, the handleSubmit function handles the post request to upload file using Axios.

How do I show image preview in React JS?

The React app we are going to build has a file input. When you select an image with this file input, an image preview will show up below it. There is also a “Remove This Image” button that lets you remove the selected image and the preview as well.


1 Answers

EDIT: To fix below issue you need to add event.persist() under handleFile function.

Uncaught TypeError: Cannot read property 'files' of null

I updated all the code using ES6.

I noticed some bad practices in your code and corrected them

  1. The way you push elements to state array is not right instead use
    previous state to play with array in react state.
  2. Stop using var
    instead use let and const
  3. Stop assigning this to self instead use arrow functions so that you no need to do manual binding and no need to depend on local variable i.e., self

I have corrected your code. This code will show the image responses as you needed

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

Please test from your side and let me know

like image 65
Hemadri Dasari Avatar answered Oct 14 '22 21:10

Hemadri Dasari