How to reset ReactJS file input

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

I have file upload input:


And I handle upload t

相关标签:
10条回答
  • 2020-12-29 01:34

    This work for me - ref={ref => this.fileInput = ref}

    <input id="file_input_file" type="file" onChange={(e) => this._handleFileChange(e)} ref={ref=> this.fileInput = ref} />
    

    then in my case once the file was uploaded to the server , I clear it by using the statement below

     this.fileInput.value = "";
    
    0 讨论(0)
  • 2020-12-29 01:36

    What worked for me was setting a key attribute to the file input, then when I needed to reset it I update the key attribute value:

    functionThatResetsTheFileInput() {
      let randomString = Math.random().toString(36);
    
      this.setState({
        theInputKey: randomString
      });
    }
    
    render() {
      return(
        <div>
          <input type="file"
                 key={this.state.theInputKey || '' } />
          <button onClick={this.functionThatResetsTheFileInput()} />
        </div>
      )
    }
    

    That forces React to render the input again from scratch.

    0 讨论(0)
  • 2020-12-29 01:37

    With every click onClick you can reset the input, so that even with the same file onChange will be triggered.

    <input onChange={this.onChange} onClick={e => (e.target.value = null)} type="file" />
    
    0 讨论(0)
  • 2020-12-29 01:40

    The following worked for me using React Hooks. This is done using what is known as a "controlled input". That means, the inputs are controlled by state, or their source of truth is state.

    TL;DR Resetting the file input was a two-step process using both the useState() and useRef() hooks.

    NOTE: I also included how I reset a text input in case anyone else was curious.

    function CreatePost({ user }) {
        const [content, setContent] = React.useState("");
        const [image, setImage] = React.useState(null); //See Supporting Documentation #1
        const imageInputRef = React.useRef(); //See Supporting Documentation #2
    
        function handleSubmit(event) {
            event.preventDefault(); //Stop the pesky default reload function
            setContent(""); //Resets the value of the first input - See #1
    
            //////START of File Input Reset
            imageInputRef.current.value = "";//Resets the file name of the file input - See #2
            setImage(null); //Resets the value of the file input - See #1
            //////END of File Input Reset
        }
    
        return (
        <div>
            <form onSubmit={handleSubmit}>
                <input 
                type="text" 
                placeholder="Add Post Content" 
                onChange={event => setContent(event.target.value)}
                value={content} //Make this input's value, controlled by state
                />
                <input 
                type="file"
                onChange={event => setImage(event.target.files[0])} //See Supporting Doc #3
                ref={imageInputRef} //Apply the ref to the input, now it's controlled - See #2
                />
                <button type="submit">Submit Form</button>
            </form>
        </div>
        )
    };
    

    Supporting Documentation:

    1. useState Hook
      • Returns a stateful value, and a function to update it.
    2. useRef Hook
      • If you pass a ref object to React, React will set its current property to the corresponding DOM node whenever that node changes.
    3. Using files from web apps
      • If the user selects just one file, it is then only necessary to consider the first file of the list.
    0 讨论(0)
  • 2020-12-29 01:40

    I know file input is always uncontrolled however the following code still works in my own porject, I can reset the input with no problems at all.

    constructor(props) {
        super(props);
        this.state = {
            selectedFile: undefined,
            selectedFileName: undefined,
            imageSrc: undefined,
            value: ''
        };
    
        this.handleChange = this.handleChange.bind(this);
        this.removeImage = this.removeImage.bind(this);
    }
    
    handleChange(event) {
        if (event.target.files[0]) {
            this.setState({
                selectedFile: event.target.files[0],
                selectedFileName: event.target.files[0].name,
                imageSrc: window.URL.createObjectURL(event.target.files[0]),
                value: event.target.value,
            });
        }
    }
    
    // Call this function to reset input
    removeImage() {
        this.setState({
            selectedFile: undefined,
            selectedFileName: undefined,
            imageSrc: undefined,
            value: ''
        })
    }
    
    render() {
        return (
            <input type="file" value={this.state.value} onChange={this.handleChange} />
        );
    }
    
    0 讨论(0)
  • 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 (
          <div>
            <input
              type="file"
              key={this.state.fileInputKey}
              class="form-control"
              onChange={this.onChangeHandler}
            />
            <button
              type="button"
              class="btn btn-success btn-block"
              onClick={this.onClickHandler}
            >
              Upload
            </button>
            <Button
              type="button"
              value="Clear"
              data-test="clear"
              onClick={this.handleClear}
            >
              {" "}
              Clear{" "}
            </Button>
    
            <br />
            <label>{this.state.message}</label>
          </div>
        );
      }
    }
    
    export default FileUpload;
    
    0 讨论(0)
提交回复
热议问题