react js handling file upload

后端 未结 7 940
长发绾君心
长发绾君心 2020-12-09 11:29

I\'m new to react js. I want to upload image asynchronously with react js Suppose I have this code

var FormBox = React.createClass({
  getInitialState: funct         


        
7条回答
  •  再見小時候
    2020-12-09 11:49

    You can make use of FileReader

    var FormBox = React.createClass({
              getInitialState: function () {
                return {
                  file: '',
                  imagePreviewUrl: ''
                }
              },
              pressButton: function () {
                e.preventDefault();
              // TODO: do something with -> this.state.file
              console.log('handle uploading-', this.state.file);
              },
              getPhoto: function (e) {
                e.preventDefault();
    
                let reader = new FileReader();
                let file = e.target.files[0];
    
                reader.onloadend = () => {
                  this.setState({
                    file: file,
                    imagePreviewUrl: reader.result
                  });
                }
    
                reader.readAsDataURL(file);
                
              },
              render: function () {
                let {imagePreviewUrl} = this.state;
                let imagePreview = null;
                if (imagePreviewUrl) {
                  imagePreview = ();
                } else {
                  imagePreview = (
    Please select an Image for Preview
    ); } return (
    {imagePreview}
    ) } }) ReactDOM.render(, document.getElementById('root'))
    
    
    

提交回复
热议问题