简体   繁体   English

JavaScript 文件上传验证

[英]File upload validation by JavaScript

I want to restrict a file upload control to allow PDF files only.我想将文件上传控件限制为仅允许 PDF 文件。 I want to use JavaScript for that.我想为此使用 JavaScript。

I want to apply that JavaScript in file upload event.我想在文件上传事件中应用该 JavaScript。

You can check the file name on submit.您可以在提交时检查文件名。

"hook to the <form>'s onsubmit with whatever method" {
  filename = theFileElement.value;
  if (!/\.pdf$/i.test(filename)) {
    alert("error");
    return false;
  }
  return true;
}

Note that this only checks if the file has an extension of .pdf .请注意,这仅检查文件是否具有.pdf扩展名。 It does not (and cannot) check whether the file is really a just PDF or actually a nasty virus.不会(也不能)检查文件是否真的只是 PDF 或实际上是令人讨厌的病毒。 Moreover, client side Javascript can easily be bypassed, so you should perform the check again on the server side.此外,客户端Javascript很容易被绕过,因此您应该在服务器端再次进行检查。

var ext = fname.split(".");
var x=ext.length;
if(ext[x-1] == 'pdf'){
  alert("Please upload doc file");
  document.form.fname.focus();
  return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM