使用ReactJS上载文件组件

Dan*_*Dan 61 ajax jquery reactjs

我一直在寻找一些帮助来制作一个组件来帮助管理从React内部上传文件到我设置的端点.

我尝试过很多选项,包括整合http://filedropjs.org.我决定反对它,因为我无法控制它在DOM中设置的元素new FileDrop('zone', options);

这是我到目前为止:

module.exports =  React.createClass({
displayName: "Upload",
handleChange: function(e){

    formData = this.refs.uploadForm.getDOMNode();

    jQuery.ajax({
        url: 'http://example.com',
        type : 'POST',
        xhr: function(){
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
            }
            return myXhr;
        },
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data){
            alert(data);
        }
    });

},
render: function(){

        return (
            <form ref="uploadForm" className="uploader" encType="multipart/form-data" onChange={this.handleChange}>
                <input ref="file" type="file" name="file" className="upload-file"/>
            </form>
        );
   }

 });



},
render: function(){

    console.log(this.props.content);

    if(this.props.content != ""){
        return (
            <img src={this.props.content} />
        );
    } else {
        return (
            <form className="uploader" encType="multipart/form-data" onChange={this.handleChange}>
                <input ref="file" type="file" name="file" className="upload-file"/>
            </form>
        );
    }
}
});
Run Code Online (Sandbox Code Playgroud)

如果有人能指出我正确的方向,我会发送一些虚拟拥抱.我一直在广泛地研究这个问题.我觉得我很亲密,但并不完全在那里.

谢谢!

Joe*_*ide 68

我也在这方面工作了很长时间.这就是我想出来的.

一个Dropzone组件,加上使用superagent.

// based on https://github.com/paramaggarwal/react-dropzone, adds image preview    
const React = require('react');
const _ = require('lodash');

var Dropzone = React.createClass({
  getInitialState: function() {
    return {
      isDragActive: false
    }
  },

  propTypes: {
    onDrop: React.PropTypes.func.isRequired,
    size: React.PropTypes.number,
    style: React.PropTypes.object
  },

  onDragLeave: function(e) {
    this.setState({
      isDragActive: false
    });
  },

  onDragOver: function(e) {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'copy';

    this.setState({
      isDragActive: true
    });
  },

  onDrop: function(e) {
    e.preventDefault();

    this.setState({
      isDragActive: false
    });

    var files;
    if (e.dataTransfer) {
      files = e.dataTransfer.files;
    } else if (e.target) {
      files = e.target.files;
    }

    _.each(files, this._createPreview);
  },

  onClick: function () {
    this.refs.fileInput.getDOMNode().click();
  },

  _createPreview: function(file){
    var self = this
      , newFile
      , reader = new FileReader();

    reader.onloadend = function(e){
      newFile = {file:file, imageUrl:e.target.result};
      if (self.props.onDrop) {
        self.props.onDrop(newFile);
      }
    };

    reader.readAsDataURL(file);
  },

  render: function() {

    var className = 'dropzone';
    if (this.state.isDragActive) {
      className += ' active';
    };

    var style = {
      width: this.props.size || 100,
      height: this.props.size || 100,
      borderStyle: this.state.isDragActive ? 'solid' : 'dashed'
    };

    return (
      <div className={className} onClick={this.onClick} onDragLeave={this.onDragLeave} onDragOver={this.onDragOver} onDrop={this.onDrop}>
        <input style={{display: 'none' }} type='file' multiple ref='fileInput' onChange={this.onDrop} />
        {this.props.children}
      </div>
    );
  }

});

module.exports = Dropzone
Run Code Online (Sandbox Code Playgroud)

使用Dropzone.

    <Dropzone onDrop={this.onAddFile}>
      <p>Drag &amp; drop files here or click here to browse for files.</p>
    </Dropzone>
Run Code Online (Sandbox Code Playgroud)

将文件添加到放置区域后,将其添加到要上载的文件列表中.我把它添加到我的焊剂商店.

  onAddFile: function(res){
    var newFile = {
      id:uuid(),
      name:res.file.name,
      size: res.file.size,
      altText:'',
      caption: '',
      file:res.file,
      url:res.imageUrl
    };
    this.executeAction(newImageAction, newFile);
  }
Run Code Online (Sandbox Code Playgroud)

您可以使用imageUrl显示文件的预览.

  <img ref="img" src={this.state.imageUrl} width="120" height="120"/>
Run Code Online (Sandbox Code Playgroud)

要上传文件,请获取文件列表并通过superagent发送.我正在使用flux,所以我从该商店获得了图像列表.

  request = require('superagent-bluebird-promise')
  Promise = require('bluebird')

    upload: function(){
      var images = this.getStore(ProductsStore).getNewImages();
      var csrf = this.getStore(ApplicationStore).token;
      var url = '/images/upload';
      var requests = [];
      var promise;
      var self = this;
      _.each(images, function(img){

        if(!img.name || img.name.length == 0) return;

        promise = request
          .post(url)
          .field('name', img.name)
          .field('altText', img.altText)
          .field('caption', img.caption)
          .field('size', img.size)
          .attach('image', img.file, img.file.name)
          .set('Accept', 'application/json')
          .set('x-csrf-token', csrf)
          .on('progress', function(e) {
            console.log('Percentage done: ', e.percent);
          })
          .promise()
          .then(function(res){
            var newImg = res.body.result;
            newImg.id = img.id;
            self.executeAction(savedNewImageAction, newImg);
          })
          .catch(function(err){
            self.executeAction(savedNewImageErrorAction, err.res.body.errors);
          });
        requests.push(promise);
      });

      Promise
        .all(requests)
        .then(function(){
          console.log('all done');
        })
        .catch(function(){
          console.log('done with errors');
        });
    }
Run Code Online (Sandbox Code Playgroud)


mik*_*123 29

这可能有所帮助

var FormUpload = React.createClass({
    uploadFile: function (e) {
        var fd = new FormData();    
        fd.append('file', this.refs.file.getDOMNode().files[0]);

        $.ajax({
            url: 'http://localhost:51218/api/Values/UploadFile',
            data: fd,
            processData: false,
            contentType: false,
            type: 'POST',
            success: function(data){
                alert(data);
            } 
        });
        e.preventDefault()
    },
    render: function() {
        return (
            <div>                
               <form ref="uploadForm" className="uploader" encType="multipart/form-data" >
                   <input ref="file" type="file" name="file" className="upload-file"/>
                   <input type="button" ref="button" value="Upload" onClick={this.uploadFile} />
               </form>                
            </div>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

从这里借来如何在jQuery中使用Ajax请求发送FormData对象?

  • 从React 0.14开始,"this.refs.file"*是*DOM节点,因此不推荐使用getDOMNode.fd.append行变为:<code> fd.append('file',this.refs.file.files [0]); </ code> (4认同)
  • 这太棒了!在我能想到的所有浏览器中都能很好地工作.谢谢! (2认同)