本文描述了使用javascript读取用户通过Input控件选择的文件的内容的方法和注意事项。后面用英文写,但我的英文不太好,如有错误之处,希望大家帮我纠正,我的联系方式在后面。
When user select a file by <input type=file>, its content can be read by javascript like this:18Please respect copyright.PENANA9dGyIayh8h
---read whole file content into array buffer---18Please respect copyright.PENANAyB0HpJLOZB
let file=input.files[0]; const reader = new FileReader(); 18Please respect copyright.PENANAS5co7Opk1p
reader.onload = () => 18Please respect copyright.PENANAXt37KLmGpX
{18Please respect copyright.PENANANps6Ac65u6
let content_whole = new Uint8Array(reader.result);18Please respect copyright.PENANAeXkbHHf1B5
}18Please respect copyright.PENANAHtwyEG90Gg
reader.readAsArrayBuffer(file);18Please respect copyright.PENANAyUs6zqj0Oz
-----------------------------------------------
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:18Please respect copyright.PENANA8sZWjFDy7N
---read part of file content into array buffer---18Please respect copyright.PENANACQODMpspmK
let file=input.files[0], block_size=1000000, start=0, end=block_size; const reader = new FileReader(); 18Please respect copyright.PENANAeK20pmOa1C
reader.onload = () => 18Please respect copyright.PENANAKqcAwtKBPy
{18Please respect copyright.PENANAOoblyP8shy
let content_part = new Uint8Array(reader.result);18Please respect copyright.PENANAJ1x9cz3WCC
}18Please respect copyright.PENANAyKE40aPzdY
reader.readAsArrayBuffer(file.slice(start,end));18Please respect copyright.PENANAm9x5aJlpZk
-----------------------------------------------
18Please respect copyright.PENANAB29p6N0L5N
Section X. Thanks18Please respect copyright.PENANA284ek2KUC4
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: si.jinmin@gmail.com18Please respect copyright.PENANAP4xhBmgROx
如果您发现本文有任何错误,或者对本文有好的建议,欢迎与我联系探讨,我的微信: si_jinmin, 我的email: si.jinmin@gmail.com
如果您對C/C++ Programming, Linux, HTTP Protocol, Website Development, Vue, Git, VsCode感興趣,邀請您加入「Linux/C/C++ Website Development」微信群,請加我的微信(si_jinmin)以便拉您进群。
ns 15.158.61.48da2