Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用ts实现导入txt文件,识别文件里的内容显示在textarea里 #40

Open
oliveying opened this issue Nov 21, 2023 · 0 comments

Comments

@oliveying
Copy link
Owner

image

export const readFile = (file: File, index1?: number) => {
  const index = index1 || 0;
  const encodes = ["utf-8", "gb2312", "gbk"];
  const encoding = encodes[index];
  var reader = new FileReader();
  reader.readAsText(file, encoding);
  reader.onloadstart = function () {
    // 开始加载,可替换loading

  };
  reader.onerror = function () {
    // loading结束
    console.error("上传文件失败,请刷新重试");
  };
  reader.onload = function () {
    // loading结束
    if (reader.result) {
      if (//.test(reader.result as any)) {
        //有乱码
        if (index + 1 <= encodes.length) {
          readFile(file, index + 1);
        } else {
          console.error(
            "检测到您的文件有乱码,本系统仅支持utf-8,gb2312,gbk三种编码方式,请检查您的文件编码"
          );
        }
      } else {
        // 限制500写死
        if ((reader.result as string).split("\n").length > 500) {
          console.error(
            "检测到您的文件>500"
          );
        }
      }
      // 获取结果
      const text = (reader.result as string).split('\n');
      // todo,处理结果里逻辑
    }
  };
}
export const identifyFiles = (files: File[]) => {
  // 获取上传的files文件
  if (files?.length === 0) {
    console.error('请选择文件');
  }
  const file = files[files.length - 1];
  if (file) {
    if (file.type != "text/plain") {
      console.error("本功能只支持导入txt文件");
      return;
    }
    readFile(file);
  }
}
@oliveying oliveying changed the title 导入txt文件,识别文件里的内容显示在textarea里 使用ts实现导入txt文件,识别文件里的内容显示在textarea里 Nov 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant