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

用 Response 代替 FileReader #18

Open
fisker opened this issue Dec 11, 2018 · 0 comments
Open

用 Response 代替 FileReader #18

fisker opened this issue Dec 11, 2018 · 0 comments

Comments

@fisker
Copy link
Owner

fisker commented Dec 11, 2018

Response: https://developer.mozilla.org/en-US/docs/Web/API/Response

FileReader: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

Response是Promise的,而FileReader是基于事件的

同样读取一个文件

使用 FileReader

;(file => {
  const fr = new FileReader()
  fr.onload = () => {
    console.log(
      'FileReader.readAsText()',
      fr.result
    )
  }
  fr.readAsText(file)
})(new File(['hello from fisker.txt'], 'fisker.txt'))

使用 Response 则优雅很多

;(async file => {
  console.log(
    'Response.text()',
    await new Response(file).text()
  )
})(new File(['hello from fisker.txt'], 'fisker.txt'))

不过两者的api有很大不同,有些api没有对应的方法

FileReader.readAsArrayBuffer() -> Body.arrayBuffer()

FileReader.readAsBinaryString() -> 无

FileReader.readAsDataURL() -> 无

FileReader.readAsText() -> Body.text()

不过也不是很难实现

readAsBinaryString

document.createElement('canvas').toBlob(async file => {
  // FileReader
  const bin1 = await new Promise(resolve => {
    const fr = new FileReader()
    fr.onload = () => {
      resolve(fr.result)
    }
    fr.readAsBinaryString(file)
  })

  console.log('FileReader.readAsBinaryString()', bin1)

  // Response
  const buffer = await new Response(file).arrayBuffer()
  const bin2 = String.fromCharCode.apply(null, new Uint8Array(buffer))
  
  console.log('Response.arrayBuffer()', bin1)

  // 校验 
  console.log(`bin1 equals bin2: ${bin1 === bin2}`)
})

readAsDataURL

;(async file => {
  // FileReader
  const url1 = await new Promise(resolve => {
    const fr = new FileReader()
    fr.onload = () => {
      resolve(fr.result)
    }
    fr.readAsDataURL(file)
  })

  console.log('FileReader.readAsDataURL()', url1)

  // Response
  const buffer = await new Response(file).arrayBuffer()
  const url2 = 'data:' + file.type + ';base64,' + 
    btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)))
  
  console.log('Response.arrayBuffer()', url2)

  // 校验 
  console.log(`url1 equals url2: ${url1 === url2}`)
})(new File(['hello from fisker.txt'], 'fisker.txt', {type: 'text/plain'}))
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