[英]Difference between readAsDataURL() and readAsArrayBuffer() and readAsText() in JavaScript FileReader
I have found a code of image uploading preview, I'm confused what's going on in FileRead()
? 我找到了一个图像上传预览代码,我很困惑
FileRead()
什么?
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
var dataURL = reader.result;
var output = document.getElementById('output');
console.log(dataURL)
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
.readAsDataURL()
return a URL representing the file's data as a base64 encoded string .readAsDataURL()
返回表示文件数据的URL作为base64编码的字符串
.readAsArrayBuffer()
return an ArrayBuffer representing the file's data .readAsArrayBuffer()
返回表示文件数据的ArrayBuffer
.readAsText()
return the file's data as a text string. .readAsText()
将文件的数据作为文本字符串返回。
For more info check this FileReader
doc. 有关详细信息,请查看此
FileReader
文档。
readAsDataURL()
will return a string that can be pasted into the url attribute of an HTML tag (eg: src=
in an img). readAsDataURL()
将返回一个字符串,该字符串可以粘贴到HTML标记的url属性中(例如: src=
in img)。 For an img
tag, that will effectively display the image just like if src
was an address to the file that was read. 对于
img
标记,它将有效地显示图像,就像src
是读取的文件的地址一样。 It is a transformation (bigger) of the original file content. 它是原始文件内容的转换(更大)。
readAsText()
will return a string of characters that can be parsed by JavaScript functions or displayed in textarea and likely to be understood by the user. readAsText()
将返回一个字符串,这些字符可以由JavaScript函数解析或显示在textarea中,并且可能被用户理解。 This is usually useful for reading text files. 这通常用于读取文本文件。
I think if you want to have a file upload functionality and then show the user a preview of the file they they chose from their PC and about to upload, then use .readAsDataURL()
. 我想如果您想要一个文件上传功能,然后向用户显示他们从PC中选择并即将上传的文件的预览,那么请使用
.readAsDataURL()
。
If you want to manipulate a text file, use .readAsText()
如果要操作文本文件,请使用
.readAsText()
If you want to manipulate something like an image (convert a jpeg to PNG for example) then use .readAsArrayBuffer()
. 如果你想操纵像图像(例如将jpeg转换为PNG),那么使用
.readAsArrayBuffer()
。
There is a fourth method, .readAsBinaryString
, but the Mozilla documentation suggests using .readAsArrayBuffer()
instead. 第四种方法是
.readAsBinaryString
,但Mozilla文档建议使用.readAsArrayBuffer()
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.