简体   繁体   中英

File upload validation by JavaScript

I want to restrict a file upload control to allow PDF files only. I want to use JavaScript for that.

I want to apply that JavaScript in file upload event.

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 . It does not (and cannot) check whether the file is really a just PDF or actually a nasty virus. Moreover, client side Javascript can easily be bypassed, so you should perform the check again on the server side.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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