【发布时间】: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