How to reset ReactJS file input

后端 未结 10 983
傲寒
傲寒 2020-12-29 00:55

I have file upload input:


And I handle upload t

10条回答
  •  礼貌的吻别
    2020-12-29 01:46

    We can reset file input by using key = {this.state.fileInputKey} and initialsing fileInputKey to Date.now() in constructor state. On file upload success , we need to again assign fileInputKey: Date.now(), so it will have different value than previous and it create new file input component on next render()

    We can also do this manually by clicking button to clear/reset file Input

    Below is the working code :

    import React from "react";
    import { Button } from "reactstrap";
    
    class FileUpload extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          selectedFile: null,
          fileInputKey: Date.now(),
          message: ""
        };
        this.handleClear = this.handleClear.bind(this);
        this.onClickHandler = this.onClickHandler.bind(this);
        this.onChangeHandler = this.onChangeHandler.bind(this);
      }
    
      onChangeHandler = event => {
        this.setState({
          selectedFile: event.target.files
        });
      };
    
      onClickHandler = () => {
        if (this.state.selectedFile === null) {
          this.setState({
            message: "Please select File"
          });
          return;
        }
        //axios POST req code to send file to server
        {
          /**        
             const data = new FormData()
        data = this.state.selectedFile[0]                
          axios.post("http://localhost:8080/api/uploadFile/", data)
                   .then(res => { 
                 if (res.status == 200) {
               // upload success
                 }                
                   })
                   .catch(err => { 
                      //message upload failed
                   })    
        */
        }
    //after upload to server processed
    
        this.setState({
          selectedFile: null,
          fileInputKey: Date.now(),
          message: "File Uploaded"
        });
      };
    
      handleClear() {
        this.setState({
          selectedFile: null,
          fileInputKey: Date.now(),
          message: ""
        });
      }
    
      render() {
        return (
          

    ); } } export default FileUpload;

提交回复
热议问题