我想FileReader
在Web应用程序中使用来将CSV文件部分加载到浏览器中。但是,我无法在Firefox 27中访问部分结果。
我的应用程序仅需要CSV文件的前100k字节来填充数据预览。因此,abort
在装入一定数量的数据后,我先设置,启动,然后再启动读取器。
这是一个在Chrome 35中可以正常运行的示例:
warn = (a...) -> console.warn a...
readFile = (file,cb,limit=1e5) ->
warn "start reading file..."
fr = new FileReader
result = null
done = -> cb null,result[..limit]
copy = (e) ->
if e.target.result? then result = e.target.result; warn "copied #{result.length} bytes"
else warn "result is empty"
fr.onloadstart = (e) -> warn "Reading #{file.name} locally..."
fr.onloadend = (e) -> warn "Reading finished (end)"; copy(e); done()
fr.onabort = (e) -> warn "Reading finished (abort)"; copy(e)
fr.onload = (e) -> warn "Reading finished (load)"; copy(e)
fr.onprogress = (e) ->
warn "progress.."; copy(e)
if e.loaded > limit
warn "Read #{e.loaded} bytes of CSV file for data preview. Aborting FileReader."
fr.abort(); fr.onprogress = null
fr.readAsText file
但是,该代码在Firefox中不起作用。中止阅读器时,所有复制的结果均为空。即使该事件表明已正确设置了某些数据并已按预期触发了该事件,也没有其他事件会e
携带。e.target.result
null
progress
e.loaded
abort()
显然,Chrome和Firefox似乎以不同的方式实现File API,即,以abort()
不同的方式处理。在Firefox中,您始终必须完全加载文件才能获得任何结果。对我来说,这是不合适的,因为我的CSV文件具有200MB或更多字节的数据,在必须完全加载数据时,我的浏览器处于冻结状态。
PS:我只关心Chrome和FF。IE和移动不在此项目范围内
编辑:这是在Chrome和Firefox中很好用的最终解决方案:
readFile = (file,cb,limit=1e4) ->
warn "start reading file..."
fr = new FileReader
done = (e) ->
warn "Read #{e.loaded} of #{file.size} bytes of CSV file for data preview"
cb null,fr.result
fr.onloadstart = (e) -> warn "Reading #{file.name} locally..."
fr.onload = (e) -> warn "Reading finished (load)"; done(e)
fr.readAsText file.slice 0,limit
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句