UploadWrap备份.js 7.0 KB
import React,{PropTypes} from 'react';
import { connect } from 'react-redux';
import cx from 'classnames';
import s from './uploader.les';
import * as fetch from '../../utils/fetch';
import { getTokenForFile } from '../../utils/fileUtil';
import { notification } from 'antd';
import customer from '../../containers/customer';

export class UploadWrap extends React.Component {
  constructor(props) {
      super(props);
      this.removeAllFile	= this.removeAllFile.bind(this);
      this.removeFile			= this.removeFile.bind(this);
      this.upload					= this.upload.bind(this);
      this.transformModel = this.transformModel.bind(this);
      this.state={
        timeStamp:Date.parse(new Date())
      }
  }
  static propTypes = {
    type       : PropTypes.string,
    maxFileSize: PropTypes.number,
    onChange   : PropTypes.func,
    backResult : PropTypes.func,
    endCallBack: PropTypes.func,
    autoUpload : PropTypes.bool,
    style      : PropTypes.object,
    extra      : PropTypes.object,
    single     : PropTypes.bool,
    extension  : PropTypes.bool,
    useFileName: PropTypes.bool,
    autoName   : PropTypes.bool,
    mimeTypes  : PropTypes.object,
    multiple   : PropTypes.bool,
    keyNum     : PropTypes.oneOfType([ PropTypes.string,PropTypes.number ]),
    max_file_size: PropTypes.string,
    maskShow: PropTypes.bool,
  }
  static defaultProps = {
    maxFileSize:10,
    autoUpload :false,
    single     :true,
    extra      :{},
    extension  :true,
    useFileName:false,
    autoName   :false,
    multiple   :false,
    mimeTypes :{},
    keyNum     :'1',
    maskShow:false,
    backResult :()=>{ },
    onChange	 :()=>{ },
    endCallBack:()=>{ },
    max_file_size:'10mb'
  }
  uploadBtn(){
    const self=this;
    const {only=false, type,extra,name='${filename}',extension,useFileName,autoName,multiple, customerUrl = '',}=this.props;
    const maskShow = self.props.maskShow
    self.props.dispatch({ type: 'MASK_SHOW', maskShow })
    getTokenForFile(type,'web_upload').then(data=>{
      let Name,fileName,extensionName;
      if(only){
        Name=name;
      }else{
        const last=self.uploader.files[0]['name']
        const num=last.lastIndexOf('.');
        const lastName=last.substring(num);
        Name=name+lastName;
        fileName=last;
        extensionName=lastName
      }
      let url = autoName?data.object_path+'/'+Date.parse(new Date()):useFileName?data.object_path+'/'+fileName:extension?data.object_path+extensionName:data.object_path
      if (customerUrl) {
        url = customerUrl
      }

      self.uploader.ossToken=data;
      const optionParam = {
            'url'				:'https://'+data.bucket+"."+data.domain+'/',
       // 'multi_selection' 	: multiple,
            'multipart_params'	:{
              'Filename'		: Name,
              OSSAccessKeyId 	:data.access_key_id,
              key			  	: url,
              policy			:data.policy,
              signature 		:data.signature,
              callback		:data.callback_body,
              'x:access_token': data.callback_token,
              'x:name'		: fileName,
              success_action_status:'200'
            }
      }
      if(multiple){
        optionParam.multipart_params.key=data.object_path+'/${filename}';
        optionParam.multipart_params['x:name']='${filename}';
        optionParam.multipart_params.Filename='${filename}';
      }
          self.uploader.setOption(optionParam);
      self.uploader.start();
    }).catch(err => { throw err; });
  }
  upload(){
    this.uploadBtn();
  }
  removeAllFile(files){
    const self	 = this;
    let delFiles = this.uploader.files;
    if(files){
      delFiles = files;
    }
    if(delFiles){
      delFiles.map((file,i)=>{
        self.uploader.removeFile(file);
      })
    }
  }
  removeFile(file){
    this.uploader.removeFile(file);
  }
  transformModel(backInfo){
    const modal = Object.assign({}, backInfo, {
      "file_id"		 : backInfo.uuid,
      "target_type": backInfo.type,
      "created_by" : backInfo.resource_owner_id,
      "target_id"	 : backInfo.InstanceId,
      "type"			 : backInfo.mime_type
    })
    return backInfo;
  }
  componentDidUpdate(prevProps, prevState){ }
  componentDidMount(){
    const self=this;
    const { single,keyNum,typeName,mimeTypes,max_file_size }=this.props;
    const dropId=this.props.dropId || '';
    const { timeStamp }=this.state;
    this.uploader = new plupload.Uploader({
      runtimes 			: 'html5,flash,silverlight,html4',
        browse_button : 'selectfiles'+keyNum+timeStamp,
        container			: self.refs['file_uploader_wrap'],
        url 					: '//oss.aliyuncs.com',
         drop_element	: dropId,//filelist  放入id  拖拽文本框的id
         filters:{
           
           max_file_size: max_file_size,

           mime_types:mimeTypes.extensions?[
             mimeTypes
           ]:[]
          },
          init: {
          PostInit: function() {
            
          },
          FileFiltered:function(uploader,file){
            
          },
          FilesAdded: function(up, files) {
            if(up.files&&up.files.length>0&&single){
              const removeFiles=up.files.slice(0,up.files.length-1);
              self.props.onChange(up.files[up.files.length-1]);
              self.removeAllFile(removeFiles);
            }
            if(self.props.autoUpload){
              self.uploadBtn();
            }
          },
          UploadProgress: function(up, file) {
            self.props.backResult(file);
          },
          FileUploaded: function(up, file, info) {
            if(info&&info.response){
              const backInfo=JSON.parse(info.response);
              if('${filename}'==backInfo.name){
                backInfo.name=backInfo.object.substring( backInfo.object.lastIndexOf('/'));
              }
              if(backInfo&&backInfo.path){
                const name=backInfo.path.substring(backInfo.path.lastIndexOf('/')+1);  //   '/' 换成 '.''
                self.props.endCallBack(self.transformModel({name,...backInfo}),typeName);
              }else
              self.props.endCallBack(self.transformModel(backInfo),typeName);
            }else{
              self.props.endCallBack({'err':'upload fail'});
            }
          },
          UploadComplete:function(up, files){ },
          Error: function(up, err){
            notification.error({
            message: '错误提示',
            description: err.code,
          });
        }
      }
    });
    this.uploader.init();
    plupload.FILE_SIZE_ERROR = `上传文件过大,请小于${max_file_size}。`;
  }
  componentWillUnmount(){
    console.log("12111111111111111113")
    this.uploader.destroy();
  }
  render(){
    const { style, keyNum, max_file_size} = this.props;
    const { timeStamp } 	 = this.state;
    console.log(max_file_size)
    return (
      <div className={cx(s.upload_wrap)} style={style} ref='file_upload_wrap' id={"selectfiles"+keyNum+timeStamp}>
        {this.props.children}
      </div>
    )
  }
}



// export default UploadWrap;
const mapState = (state) => {
  return {
  };
}
export default connect(mapState)(UploadWrap);