Detecting a file's content-type when using JavaScript's FileReader interface

本秂侑毒 提交于 2019-11-30 20:06:01
if (file.type.match('text/plain')) {
    // file type is text/plain
} else {
    // file type is not text/plain
}

String.match is a RegEx, so if you would want to check, if the file is any type of text, you could do that:

if (file.type.match('text.*')) {
    // file type starts with text
} else {
    // file type does not start with text
}

The Content Type can be read with the following code:

// 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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!