使用ReactJS上传文件组件

使用ReactJS上传文件组件,第1张

使用ReactJS上传文件组件

我也为此工作了一段时间。这是我想出的。

一个

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

使用

Dropzone

    <Dropzone onDrop={this.onAddFile}>      <p>Drag &amp; drop files here or click here to browse for files.</p>    </Dropzone>

将文件添加到放置区后,将其添加到要上传的文件列表中。我将其添加到我的助焊剂存储中。

  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);  }

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

  <img ref="img" src={this.state.imageUrl} width="120" height="120"/>

要上传文件,请获取文件列表,然后通过超级代理发送它们。我使用的是助焊剂,因此我从该商店获取图像列表。

  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');        });    }


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5639424.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存