1

I would like to upload a image-file to storage of the firebase and put {title , content, createDate etc} in firestore. but it seems that state.upload file prevents putting it in firestore.

this.setState({ uploadfile: "" })

The error says

FirebaseError: Function addDoc() called with invalid data. Unsupported field value: a custom File object (found in field uploadfile in document projects/c0hQXdRAgIe1lIzq1vTy)

class CreateProject extends Component {
    state = {
        title:'',
        content:'',
        uploadfile:'',
        setImageUrl:'',
    }

    handleChange = (e) =>{
        this.setState({
            [e.target.id]: e.target.value
        })
    }

    handleSubmit = (e) =>{
        e.preventDefault();
        this.setState({ uploadfile: "" })
        this.props.createProject(this.state)
        this.props.history.push('/')
    }

    onDrop = acceptedFiles => {
      if (acceptedFiles.length > 0) {
        this.setState({ uploadfile: acceptedFiles[0] })
      }
    }
  
    handleSubmitImg = (e) =>{
      e.preventDefault()
      //this.props.sampleteFunction()
    };

    parseFile = (file) =>{
      const updatedFile = new Blob([file], { type: file.type });
      updatedFile.name = file.name;
      return updatedFile;
    }



    onSubmit = (event) => {
      event.preventDefault();
      var updatedFile = this.state.uploadfile;
      if (updatedFile === "") {
      }
      console.log("aaaaaaaaaaaa"+updatedFile)
      const uploadTask = storage.ref(`/images/${updatedFile.name}`).put(updatedFile);
      uploadTask.on(
        firebase.storage.TaskEvent.STATE_CHANGED,
        this.next,
        this.error,
        this.complete
      );
    };
    next = snapshot => {
      const percent = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    };
    error = error => {
      console.log(error);
    };
    complete = () => {
      var updatedFile = this.state.uploadfile
      storage
        .ref("images")
        .child(updatedFile.name)
        .getDownloadURL()
        .then(fireBaseUrl => {
          this.setState({ setImageUrl: fireBaseUrl })
          //this.state.setImageUrl(fireBaseUrl);
        });
    };

  
    
  render() {
   const maxSize = 3 * 1024 * 1024;
   const dropzoneStyle = {
    width: "100%",
    height: "auto",
    borderWidth: 2,
    borderColor: "rgb(102, 102, 102)",
    borderStyle: "dashed",
    borderRadius: 5,
  }

    const {auth} = this.props

    console.log("UP"+this.state.uploadfile  );
    if(!auth.uid) return <Redirect to="/signin" />
    return (
      <Dropzone
      onDrop={this.onDrop}
      accept="image/png,image/jpeg,image/gif,image/jpg"
      inputContent={(files, extra) => (extra.reject ? 'Image files only' : 'Drag Files')}
      styles={dropzoneStyle}
      minSize={1}
      maxSize={maxSize}
    >
      {({ getRootProps, getInputProps }) => (

      <div className="container">
        <form onSubmit={this.handleSubmit} className="white">
            <h5 className="grey-text text-darken-3">
                Create Project
            </h5>
            <div className="input-field">
                <label htmlFor="title">Title</label>
                <input type="text" id="title" onChange={this.handleChange}/>
            </div>

            <div className="input-field">
                <label htmlFor="content">Project Content</label>
                <textarea id="content" className="materialize-textarea" onChange={this.handleChange}></textarea>
            </div>
            <div className="input-field">
                <button className="btn pink lighten-1 z-depth-0">Create</button>
            </div>
        </form>
            <div {...getRootProps()}>
                <input {...getInputProps()} />
                
                <p>File Drag</p>
                {this.state.uploadfile ? <p>Selected file: {this.state.uploadfile.name}</p> : null}
                
                {this.state.uploadfile ? (<Thumb key={0} file={this.state.uploadfile } />) :null}
            </div>
            <form onSubmit={this.onSubmit}>
           <button>Upload</button>
          </form>
 
      </div>
  )}
</Dropzone>
    )
  }
}

const matchStateToProps = (state) => {
    return{
        auth: state.firebase.auth
    }
}

const mapDispatchToProps = (dispatch) => {
    return{
        createProject: (project) => dispatch(createProject(project))
    }
}

export default connect(matchStateToProps, mapDispatchToProps)(CreateProject)

Action

export const createProject = (project) => {
    return (dispatch, getState, { getFirebase, getFirestore }) => {
        // make async call to database
        const firestore = getFirestore(); 
        const profile = getState().firebase.profile;
        const authorId = getState().firebase.auth.uid;
        firestore.collection('projects').add({
            ...project,
            authorUserName: profile.userName,
            authorId: authorId,
            createdAt: new Date()
        }).then(() => {
            dispatch({ type: 'CREATE_PROJECT', project})
        }).catch((err) => {
            dispatch({ type: 'CREATE_PROJECT_ERROR', err })
        })
    }
};

user14232549
  • 405
  • 4
  • 17
  • I think it has to do with the way the object is received the issue is that its trying to upload a string instead of an actual file. I found [this](https://dev.to/clintdev/simple-firebase-image-uploader-display-with-reactjs-3aoo) example where they have the state setup a bit differently maybe it is what you are looking for? – Hipster Cat Mar 05 '21 at 20:30
  • Not really, firebase.profile is always discarded automatically as well as unnecessary state is set. – user14232549 Mar 06 '21 at 06:45
  • I read [here](https://github.com/FirebaseExtended/firebase-dart/issues/224) and according to the link I sent you [here](https://dev.to/clintdev/simple-firebase-image-uploader-display-with-reactjs-3aoo) should try to change `this.setState({ uploadfile: "" })` for `this.setState({ uploadfile: null })` – Hipster Cat Mar 08 '21 at 22:50

0 Answers0