问题描述
我一直在为网络应用程序中的纯文本文件设置导入脚本。
I've been setting up an import script for plain-text files in a web application.
我的脚本如下:
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)
}
}
它实质上是对的修改。
但是,目前用户可以在技术上尝试导入任何文件。因为它是为纯文本文件设计的,所以如果导入了不同类型的文件,就会出现问题。
However, at the moment the user can technically attempt to import any file. As it's designed for plain-text files, problems can arise if a different type of file is imported.
我在控制台中注意到浏览器检测到内容 - 要导入的文件的类型。这是一个例子。
I've noticed in the console that the browser detects the content-type of the file being imported. Here's an example.
fileName: "ideas.txt"
fileSize: 377
name: "ideas.txt"
size: 377
type: "text/plain"
webkitRelativePath: ""
那么,是否有可能设置一个参数,其中脚本检测到文件的内容类型,如果它不是许多指定的合适内容类型之一,则具有脚本拒绝导入吗?
Is it possible, then, to set up an argument where the script detects the content-type of the file, and if it isn't one of a number of specified suitable content-types, have the script refuse to import it?
提前感谢任何建议。
推荐答案
if (file.type.match('text/plain')) {
// file type is text/plain
} else {
// file type is not text/plain
}
String.match是一个RegEx ,所以如果你想检查,如果文件是任何类型的文本,你可以这样做:
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
}
这篇关于使用JavaScript的FileReader接口时检测文件的内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!