本文描述了使用javascript读取用户通过Input控件选择的文件的内容的方法和注意事项。后面用英文写,但我的英文不太好,如有错误之处,希望大家帮我纠正,我的联系方式在后面。
When user select a file by <input type=file>, its content can be read by javascript like this:53Please respect copyright.PENANARBUYAAu1P6
---read whole file content into array buffer---53Please respect copyright.PENANAZfVYLnWcvr
let file=input.files[0]; const reader = new FileReader(); 53Please respect copyright.PENANAhdItmhy6Dm
reader.onload = () => 53Please respect copyright.PENANAv035ozyc0h
{53Please respect copyright.PENANAN8yB3t5ejl
let content_whole = new Uint8Array(reader.result);53Please respect copyright.PENANAgRwuoRnwIV
}53Please respect copyright.PENANAQZDNdd6k5q
reader.readAsArrayBuffer(file);53Please respect copyright.PENANAo2WuJpSR08
-----------------------------------------------
If the file size is too large, the browser may crash as the whole file content are loaded into memory by array buffer. In order to avoid it, we can just read a part of the file like this:53Please respect copyright.PENANARy03rfJTaI
---read part of file content into array buffer---53Please respect copyright.PENANAfv55nc8MlL
let file=input.files[0], block_size=1000000, start=0, end=block_size; const reader = new FileReader(); 53Please respect copyright.PENANAV8sIUgQkLn
reader.onload = () => 53Please respect copyright.PENANAqdUqGPq5o8
{53Please respect copyright.PENANAr6vxs6IWk3
let content_part = new Uint8Array(reader.result);53Please respect copyright.PENANAIzN59kYF6J
}53Please respect copyright.PENANAyV3cvwrQf9
reader.readAsArrayBuffer(file.slice(start,end));53Please respect copyright.PENANACchtiXP9mI
-----------------------------------------------
53Please respect copyright.PENANAYBMuVjM8ZY
Section X. Thanks53Please respect copyright.PENANAruVr9BOj3f
https://segmentfault.com/a/1190000022113605
Section Y. Contacts Me
If you found any errors or have any suggestions for this article, please let me know, my wechat: si_jinmin, my email: [email protected]53Please respect copyright.PENANA4JicNUM4zG
如果您发现本文有任何错误,或者对本文有好的建议,欢迎与我联系探讨,我的微信: si_jinmin, 我的email: [email protected]
如果您對C/C++ Programming, Linux, HTTP Protocol, Website Development, Vue, Git, VsCode感興趣,邀請您加入「Linux/C/C++ Website Development」微信群,請加我的微信(si_jinmin)以便拉您进群。
ns18.119.119.0da2