我一直在为 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: ""
那么,是否可以设置一个参数,让脚本检测文件的内容类型,并且如果它不是多个指定的合适内容类型之一,脚本是否会拒绝导入它?
预先感谢您的任何建议。
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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)