简体   繁体   English

如何选择FileReader的阅读方法?

[英]How to Pick a FileReader Reading Method?

While making a simple picture uploader, I am learning about FileReader API. 在制作一个简单的图片上传器时,我正在学习FileReader API。 There are 4 formats, which are array buffer, binary string, data URL, and text, to upload a file, and I would like to know how to pick one. 上传文件有4种格式,分别是数组缓冲区,二进制字符串,数据URL和文本,我想知道如何选择一种。

Among few articles, this says that data URL is good when you want to show the uploaded picture and array buffer is good when you manipulate the file. 在几篇文章中, 表示当您想显示上传的图片时,数据URL是好的,而当您操纵文件时,数组缓冲区是好的。 What do you think? 你怎么看? And, when is a good occasion to choose binary string or text formats? 并且,什么时候是选择二进制字符串或文本格式的好时机?

For a "File Uploader", you should simply not use a FileReader at all. 对于“文件上传器”,您根本不应该使用FileReader。

You don't need to read the file to be able to upload it, you can send it as a Blob directly . 您无需阅读文件即可上传, 可以直接将其作为Blob发送

If you need to display it in the current page, you still don't need a FileReader, create a blobURI from the Blob , which will point directly to the File on disk, with no useless memory bloating. 如果需要在当前页面中显示它,则仍然不需要FileReader, 请从Blob创建一个blobURI ,它将直接指向磁盘上的文件,而不会浪费内存。

 inp.onchange = e => { // yes that's all synchronous... const url = URL.createObjectURL(inp.files[0]); const img = new Image(); img.src = url; document.body.appendChild(img); }; 
 <input type="file" id="inp" accept="image/*"> 


The only use cases for a FileReader is when you need to access the content of the File, for instance, FileReader的唯一用例是当您需要访问File的内容时,例如,

  • if you want to load a text file (or csv, or json) and parse it, then you will use the readAsText() method. 如果要加载文本文件(或csv或json)并进行解析,则将使用readAsText()方法。
  • if you want to read/edit some binary file (eg read meta-data of a JPEG file?), then you'll use readAsArrayBuffer() , and work from this buffer. 如果您想读取/编辑某个二进制文件(例如,读取JPEG文件的元数据?),则将使用readAsArrayBuffer()并从此缓冲区工作。
  • readAsDataURL() is unfortunately too much misused, As said previously, in 99% of the cases, what you'll do from this dataURI could be done with a blobURI, or the Blob directly. 不幸的是, readAsDataURL()滥用过多,如前所述,在99%的情况下,可以使用blobURI或直接使用Blob完成此dataURI的操作。 The only one case I can see for it, is to append binary data in some standalone document... Or, something that doesn't happen everyday on every website... 我能看到的唯一一种情况是在一个独立的文档中附加二进制数据...或者,并不是每个网站每天都发生的事情...
  • readAsBinaryString() is rather useless, and had even been removed form the standards. readAsBinaryString()相当无用,甚至已从标准中删除。 If you really need a binary string representation of your File, you can generate one from an ArrayBuffer, but what you'll do with this String is a mystery. 如果确实需要File的二进制字符串表示形式,则可以从ArrayBuffer生成一个二进制字符串表示形式,但是使用此String字符串所做的事情是一个谜。 (work with ArrayBuffer directly). (直接与ArrayBuffer一起使用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM