【问题标题】:Detecting a file's content-type when using JavaScript's FileReader interface使用 JavaScript 的 FileReader 接口检测文件的内容类型
【发布时间】:2011-05-14 22:31:22
【问题描述】:

我一直在为 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)
    }
}

它本质上是对this question 的修改。

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

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

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

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

提前感谢您的任何建议。

【问题讨论】:

  • 我认为,通过“检测内容类型”你的意思是,从文件的扩展名推断..
  • 通过扩展推断是一种方法,但我希望我可以访问任何告诉浏览器文件是的内容,例如“text/plain”或“text/x” -tex" 或 "image/jpeg" 等等。

标签: javascript import content-type plaintext filereader


【解决方案1】:

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

// 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);

【讨论】:

  • 另一个选项(更简单)是检查:dataURL.split(",")[0].split(":")[1].split(";")[0]。 indexOf([你的 MIME 类型]>=0
【解决方案2】:
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
}

【讨论】:

    猜你喜欢
    • 2012-03-11
    • 2014-09-25
    • 2011-09-18
    • 2014-07-25
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 2015-07-25
    相关资源
    最近更新 更多