无法在'FileReader'上执行'readAsBinaryString':参数1不是'Blob'类型的

时间:2019-10-04 06:43:01

标签: javascript reactjs xls

我正在尝试解析xls文件,请参见以下文件 https://filebin.net/jm37356p8nkzgycm

遇到错误

无法在'FileReader'上执行'readAsBinaryString':参数1的类型不是'Blob'。

这是我的代码 https://stackblitz.com/edit/react-e9zsto

handleFile = (file /*:File*/) => {
    /* Boilerplate to set up FileReader */
    const reader = new FileReader();
    const rABS = !!reader.readAsBinaryString;
    reader.onload = e => {
      /* Parse data */
      const bstr = e.target.result;
      const wb = XLSX.read(bstr, { type: rABS ? "binary" : "array" });
      /* Get first worksheet */
      let arr = xslToJson(wb);
    };
    if (rABS) reader.readAsBinaryString(file);
    else reader.readAsArrayBuffer(file);
  };

1 个答案:

答案 0 :(得分:1)

您的handleFile函数不接收文件而是接收事件作为参数。更改为如下所示:

handleFile = (e) => {
  const file = e.target.files[0];
  /* Boilerplate to set up FileReader */
  const reader = new FileReader();
  const rABS = !!reader.readAsBinaryString;
  reader.onload = e => {
    /* Parse data */
    const bstr = e.target.result;
    const wb = XLSX.read(bstr, { type: rABS ? "binary" : "array" });
    /* Get first worksheet */
    let arr = this.xslToJson(wb);
  };
  if (rABS) reader.readAsBinaryString(file);
  else reader.readAsArrayBuffer(file);
};