From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/file/getastext/index.html | 45 +++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 files/zh-cn/web/api/file/getastext/index.html (limited to 'files/zh-cn/web/api/file/getastext') diff --git a/files/zh-cn/web/api/file/getastext/index.html b/files/zh-cn/web/api/file/getastext/index.html new file mode 100644 index 0000000000..a71b8f254e --- /dev/null +++ b/files/zh-cn/web/api/file/getastext/index.html @@ -0,0 +1,45 @@ +--- +title: File.getAsText +slug: Web/API/File/getAsText +translation_of: Web/API/File/getAsText +--- +

{{APIRef("File API")}}

+ +

概述

+ +

按照指定的编码类型将文件内容解析成字符串并返回.

+ +

示例

+ +
// fileInput是一个HTMLInputElement元素: <input type="file" id="myfileinput" multiple>
+var fileInput = document.getElementById("myfileinput");
+
+// files是一个FileList对象(类似NodeList)
+var files = fileInput.files;
+
+// 一个对象,包含了允许的MIME类型
+var accept = {
+    binary : ["image/png", "image/jpeg"],
+    text :   ["text/plain", "text/css", "application/xml", "text/html"]
+};
+
+var file;
+
+for (var i = 0; i < files.length; i++) {
+
+    file = files[i];
+
+    // 如果文件的类型能够被检测到
+   if (file !== null) {
+
+        if (accept.text.indexOf(file.mediaType) > -1) {
+
+            // file是个可接受的文本文件,使用utf-8编码读取
+            var data = file.getAsText("utf-8");
+            // 使用字符串方法处理data
+
+        } else if (accept.binary.indexOf(file.mediaType) > -1) {
+            // file是个可接受的二进制文件
+        }
+    }
+}
-- cgit v1.2.3-54-g00ecf