使用JavaScript的FileReader接口时检测文件的内容类型

木川 *_* 炎星 8 javascript import content-type plaintext filereader

我一直在为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)
    }
}
Run Code Online (Sandbox Code Playgroud)

它基本上是对这个问题的修改.

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

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

fileName: "ideas.txt"
fileSize: 377
name: "ideas.txt"
size: 377
type: "text/plain"
webkitRelativePath: ""
Run Code Online (Sandbox Code Playgroud)

它是可能的,那么,建立在脚本检测内容类型文件的参数,如果它不是一个数字指定合适的内容类型中的一种,该脚本拒绝进口呢?

提前感谢任何建议.

tre*_*mbl 14

if (file.type.match('text/plain')) {
    // file type is text/plain
} else {
    // file type is not text/plain
}
Run Code Online (Sandbox Code Playgroud)

String.match是一个RegEx,所以如果你想检查一下,如果文件是任何类型的文本,你可以这样做:

if (file.type.match('text.*')) {
    // file type starts with text
} else {
    // file type does not start with text
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*uer 11

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

// 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);
Run Code Online (Sandbox Code Playgroud)