反应js处理文件上传 [英] react js handling file upload

查看:39
本文介绍了反应js处理文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来反应js的人.我想用react js异步上传图像假设我有这段代码

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: function () {
    return {
      photo: []
    }
  },
  pressButton: function () {
    var data = new FormData();
    data.append("photo", this.state.photo);
    // is this the correct way to get file data?
  },
  getPhoto: function (e) {
    this.setState({
      photo: e.target.files[0]
    })
  },
  render: function () {
    return (
      <form action='.' enctype="multipart/form-data">
        <input type='file'  onChange={this.getPhoto}/>
        <button onClick={this.pressButton}> Get it </button>
      </form>
    )
  }
})

ReactDOM.render(<FormBox />, document.getElementById('root'))

任何答案将不胜感激!

推荐答案

您可以使用 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 = (<img src={imagePreviewUrl} />);
            } else {
              imagePreview = (<div className="previewText">Please select an Image for Preview</div>);
            }
            return (
              <div>
              <form action='.' enctype="multipart/form-data">
                <input type='file'  onChange={this.getPhoto}/>
                <button onClick={this.pressButton}> Get it </button>
              </form>
              <div className="imgPreview">
                {imagePreview}
              </div>
              </div>
            )
          }
        })
        
        ReactDOM.render(<FormBox />, document.getElementById('root'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="root"></div>

这篇关于反应js处理文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆