Failed to save image to state and send it as a request to a third-party API

I am working on a React-Redux application. I am currently working on submitting a form. I save data from a form to a state. But I can’t keep the photo in the state. I tried converting the file to a base64 string, but it does not seem to work. I check the status by getting output on my console. And for the image file, the console shows me Array [1] . It should show me the base64 string. Here is this piece of code:

export class SignUp extends React.Component {

  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleImageChange = this.handleImageChange.bind(this);
  }

  handleSubmit(user) {
    const { dispatch } = this.props;

    const somePromise = new Promise((resolve) => {

    console.log(user);


    this.setState({}, this.sendFormData);

    });
    dispatch(actions.submit('user', somePromise));


  }

  handleImageChange(e) {
    e.preventDefault();

    let reader = new FileReader();
    let imgFile = e.target.files[0];


    reader.onloadend = () => {
      this.setState({
        file: reader.readAsDataURL(imgFile)
      });
    }

  }

  render() {


    let { user } = this.props;

    return (

      <Form model="user" onSubmit = {this.handleSubmit}>

        <div className={classes.signup}>

        <Field className = {classes.pictureDiv} model="user.file">
          <label className = {classes.labelTop}>PROFILE PICTURE</label>
          <img src={userImage} className = {classes.imageArea}/>
          <input type="file" onChange={this.handleImageChange} ref="pic"/>
          <button className = {classes.delButton}>Delete</button>
        </Field>

        //...so on

And besides, I can’t figure out how to get this base64 string value of the image file and change it into the request URL, as I do with the other fields here:

 sendFormData(){


    var formData = {
      fn: ReactDOM.findDOMNode(this.refs.fn).value,
      ln: ReactDOM.findDOMNode(this.refs.ln).value,
      city: ReactDOM.findDOMNode(this.refs.city).value,
      pic: ReactDOM.findDOMNode(this.refs.pic)  //-------------@todo don't know what to do here
    };

    //for check boxes
    formData.yes = this.getSelected('yes');
    formData.no = this.getSelected('no');

    // Send the form data.
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.open('POST','http://jsonplaceholder.typicode.com/posts',true);
    xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4) {
        var response = JSON.parse(xmlhttp.responseText);



        if (xmlhttp.status == 200 || xmlhttp.status == 201) {
          console.log('success');
        }
        else {
          console.log('failure')

        }


      }

    };

    xmlhttp.send(this.requestBuildQueryString(formData));
  }


  requestBuildQueryString(params) {
  var queryString = [];
  for(var property in params)
    if (params.hasOwnProperty(property)) {
      queryString.push(encodeURIComponent(property) + '=' + encodeURIComponent(params[property]));
    }
  return queryString.join('&');

  }
+4

Source: https://habr.com/ru/post/1650171/


All Articles