New FileReader() 能帮我们执行啥?

82 阅读1分钟

1:FileReader : 读取文件内容

    readAsText() 读取文本文件,(可以使用Txt打开的文件)

    readAsBinaryString(): 读取任意类型的文件,返回二进制字符串
    
    readAsDataURL: 方法可以将读取到的文件编码成DataURL ,可以将资料(例如图片、excel文件)内嵌在网页之中,不用放到外部文件
 
    abort: 中断读取

2:FileReader 提供一个完整的事件模型,用来捕获读取文件的状态

    onabort:读取文件断片时触发

    onerror:读取文件错误时触发

    onload:文件读取成功时触发

    onloadend:文件读取完毕之后,不管成功还是失败触发

    onloadstart: 开始读取文件时触发

    onprogress:读取文件过程中触发

示例:

   new Promise((resolve)=>{
    let reader = new FileReader()
    reader.readAsDataURL(file.raw) // 必须用file.raw
    reader.onload = () => { // 让页面中的img标签的src指向读取的路径
        let img = new Image()
        img.src = reader.result
        // console.log(`当前文件尺寸大小:${img.width}×${img.height}`)
        if (img.complete) { // 如果存在浏览器缓存中
          if (img.width < 690 || img.height < 690) {
            resolve(false)
          } else {
            resolve(true)
          }
        } else {
          img.onload = () => {
            if (img.width < 690 || img.height < 690) {
              resolve(false)
            } else {
              resolve(true)
            }
          }
        }
    }
  })