请注意,csv文件有许多MimeTypes,因此您应该检查更多的类型,而不仅仅是
"application/vnd.ms-excel"
=>
.CSV Mimetypes,并且您可以通过将文件类型与接受类型的数组进行比较,在客户端上检查它,这样您就可以添加或删除适合您需求的方式。
const acceptedTypes = ["text/csv", "text/x-csv", "application/x-csv", "application/csv", "text/x-comma-separated-values", "text/comma-separated-values", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel"];
document.querySelector("[type='file']").onchange = function() {
if(!acceptedTypes.includes(this.files[0].type)) {
console.log("This file is not allowed for upload");
this.value = "";
}
};
如果您希望仅在用户拖放文件时出现此行为,则可以像这样自定义它。
const acceptedTypes = ["text/csv", "text/x-csv", "application/x-csv", "application/csv", "text/x-comma-separated-values", "text/comma-separated-values", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel"];
let isDragged = false;
document.querySelector("[type='file']").ondragover = function() {
isDragged = true;
};
document.querySelector("[type='file']").onchange = function() {
if(!isDragged) return;
if(!acceptedTypes.includes(this.files[0].type)) {
console.log("This file is not allowed for upload");
this.value = "";
}
isDragged = false;
};