JavaScript读取本地文件

前端使用input

//不要用<input></input>,会报错,直接用<input />
  const filesInput = useRef(null) as React.RefObject<HTMLInputElement>;//用useRef
  const acceptType = ".txt";

  <DefaultButton
    onClick={() => filesInput.current.click()}
    className="browse-files-button"
  >
    Browse files...
    <input type="file" onChange={readFile} ref={filesInput} accept={acceptType} onClick={(e: any) => (e.target.value = null)}/>
  </DefaultButton>

函数:

    readFile(e: any) {
        const reader = new FileReader();
        let input = e.target.files[0];//文件
        reader.readAsText(input);//text读取,函数使用取决于文件类型
        reader.onload = function (e: any) {
            let text = e.target.result;//文件内容
            let arr = (text as string).split("\n");//切分
            let newArr = arr.filter(i => i && i.trim())//删除空行,空格等
            let item = {
                uid: uuidv1(),
                name: input.name,
                text: newArr
            }
            let list = this.state.fileList;
            list.push(item);
            this.setState({ fileList: list });
        }.bind(this);//后面bind,如果是类里的func需要,如果是func里的就不需要,看set报不报错
    }
posted @ 2020-07-23 18:17  Shaw_喆宇  阅读(699)  评论(0编辑  收藏  举报