8

我一直在为 Web 应用程序中的纯文本文件设置导入脚本。

我的脚本如下:

function dataImport(files) {
    confirm("Are you sure you want to import the selected file? This will overwrite any data that is currently saved in the application workspace.");
    for (i = 0; i < files.length; i++) {
        file = files[i]
        console.log(file)
        var reader = new FileReader()
        ret = []
        reader.onload = function(e) {
            window.localStorage.setItem("ApplicationData", e.target.result);
        }
        reader.onerror = function(stuff) {
            console.log("error", stuff)
            console.log (stuff.getMessage())
        }
        reader.readAsText(file)
    }
}

它本质上是对这个问题提出的修改。

但是,目前用户在技术上可以尝试导入任何文件。由于它是为纯文本文件设计的,如果导入不同类型的文件,可能会出现问题。

我在控制台中注意到浏览器检测到正在导入的文件的内容类型。这是一个例子。

fileName: "ideas.txt"
fileSize: 377
name: "ideas.txt"
size: 377
type: "text/plain"
webkitRelativePath: ""

那么,是否有可能在脚本检测文件的内容类型时设置一个参数,如果它不是许多指定的合适的内容类型之一,脚本是否会拒绝导入它?

提前感谢您的任何建议。

4

2 回答 2

15
if (file.type.match('text/plain')) {
    // file type is text/plain
} else {
    // file type is not text/plain
}

String.match 是一个正则表达式,所以如果你想检查文件是否是任何类型的文本,你可以这样做:

if (file.type.match('text.*')) {
    // file type starts with text
} else {
    // file type does not start with text
}
于 2011-05-06T06:38:20.583 回答
12

可以使用以下代码读取内容类型:

// Note: File is a file object than can be read by the HTML5 FileReader API
var reader = new FileReader();

reader.onload = function(event) {
  var dataURL = event.target.result;
  var mimeType = dataURL.split(",")[0].split(":")[1].split(";")[0];
  alert(mimeType);
};

reader.readAsDataURL(file);
于 2014-01-30T15:18:16.853 回答