Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload and read a file in react

Im trying to upload a file with React and see its contents, but what it gives me is C:\fakepath\. I know why it gives fakepath, but what is the correct way to upload and read the contents of a file in react?

<input type="file"
      name="myFile"
      onChange={this.handleChange} />

handleChange: function(e) {
        switch (e.target.name) {
        case 'myFile':
            const data = new FormData();
            data.append('file', e.target.value);
            console.log(data);
        default:
            console.error('Error in handleChange()'); break;
        }
    },
like image 378
ssss Avatar asked Sep 08 '17 15:09

ssss


People also ask

How do I read content of uploaded file in react JS?

To fetch the file data, use the Async library to launch the File Reader API from React. Assign a new FileReader() object to a variable, then use an onload function to grab the file information from an array of selected files or e. target. files[0] in this case.

How do I open an upload file in React?

To open a file input box on button click in React: Set the onClick prop on a button element. Set the ref prop on the file input. When the button gets clicked, open the file input box, e.g. inputRef.

How do I find the path of an uploaded file in React?

You can retrieve the saved file path in the uploader success event and assign it to custom attribute (data-file-name) value of the respective file list element to open the uploaded file. Click the respective file element to create a new request along with saved file path using http header.


1 Answers

To get the file info you want to use event.target.files which is an array of selected files. Each one of these can be easily uploaded via a FormData object. See below snippet for example:

class FileInput extends React.Component {
    constructor(props) {
      super(props)
      this.uploadFile = this.uploadFile.bind(this);
    }
    
    uploadFile(event) {
        let file = event.target.files[0];
        console.log(file);
        
        if (file) {
          let data = new FormData();
          data.append('file', file);
          // axios.post('/files', data)...
        }
    }
    
    render() {
      return <span>
        <input type="file"
        name="myFile"
        onChange={this.uploadFile} />
      </span>
    }
}

ReactDOM.render(<FileInput />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>
<div id="root"></div>

You may want to look into FileReader which can help if you want to handle the file on the client side, for example to display an image.

https://developer.mozilla.org/en-US/docs/Web/API/FileReader

like image 142
Purgatory Avatar answered Sep 18 '22 15:09

Purgatory