欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

react下 ie不支持FileReader的解决办法

程序员文章站 2024-03-25 12:59:46
...

转载 : https://www.jianshu.com/p/ca0dfff147c8

安装xlsx
npm intall xlsx --save

文件代码

// 导入文件
import XLSX from 'xlsx'; 

// react读取文件内容 

@connect(state => state)
export default class ImportExcel extends Component {

   constructor(props) {
      super(props);
      this.state = {
          uploadList : [],
      };
  }

  _importExcel = (e) => {
      const self = this;
      const files = e.target.files[0];
      
      const fileReader = new FileReader();
      // 如果IE 浏览器 不支持FileReader
      const File_Status = FileReader.prototype.readAsBinaryString;
      File_Status ? fileReader.readAsBinaryString(files) : fileReader.readAsArrayBuffer(files);

      fileReader.onload = function(ev) {
      fileReader.onload = function(ev) {
          try {
              let data = ev.target.result,
                  workbook = XLSX.read(data, {type: File_Status ? "binary" : "array"}),
                  persons = []; // 存储获取到的数据

              // 表格的表格范围,可用于判断表头是否数量是否正确
              let fromTo =  "";
              // 遍历每张表读取
              for (let sheet in workbook.Sheets) {
                  if (workbook.Sheets.hasOwnProperty(sheet)) {
                      fromTo = workbook.Sheets[sheet]['!ref'];
                      persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                  }
              }
              console.log(persons);
              self.setState({uploadList:persons},() => self._saveXLSXData())
          } catch (e) {
              self.file.value = "";
              console.log("文件类型不正确!");
              return;
          }
      };
  };

  /**
   * 保存并上传的数据到数据库
   * @private  该方法是把数据发送到服务器, 请求方法自己处理 
   */
  _saveXLSXData = () => {
      const {uploadList} = this.state;
      let data = {
          data : uploadList,
      };
      const self = this;
      return new Promise( async (ps,pe)=>{
          this.file.value = "";
          let res = await AxiosFn('/maintain/saveStudents', data , "POST").catch((e) => {});
          if (res && (res.code === 0)) {
              message.success("数据添加成功!");
              this.setState({uploadList : []});
              self.getPageData();
          }
          ps();
      });
  };


  render(){
      return(
          <div style={{marginRight: 15,width:120, border:"1px solid #ccc",borderRadius:5,padding:"6px 12px",position:"relative"}}>
              数据导入
              <input
                  ref={(file) => this.file = file }
                  type="file"
                  onChange={this.importExcel}
                  style={{position: 'absolute', top: 0, left: 0,width: '100%',zIndex:999,opacity:0}}
              />
          </div>
      )
  }
  };
相关标签: react