在JSP中使用HTML type=file上传文件,并在上传前在javascript中执行一些检查

File upload using HTML type=file in JSP and executing some checks in javascript before upload...

本文关键字:javascript 执行 检查 文件 HTML type JSP file      更新时间:2023-09-26

目前我们有这个代码来上传文件

<input id='fileBrowse' type='file' style="width:187px;height:20px" class='fileBrowse' onchange="onBrowseFile( this );" />

执行一些检查的 JavaScript 函数如下所示:

    function onBrowseFile( fb ) {
    var myFSO = new ActiveXObject("Scripting.FileSystemObject");
    var thefile = myFSO.getFile(fb.value);
    if( (thefile.size / 1000000) > maxfilesize) {
        alert( "The size of the files you have tried to drag and drop exceed the maximum allowed. Please drag no more than "+maxfilesize+" MB at a time." );
        return;
    }
    if( fb.value.indexOf( ".exe" ) > -1 ||
            fb.value.indexOf( ".asp" ) > -1 ||
            fb.value.indexOf( ".aspx" ) > -1 ||
            fb.value.indexOf( ".cab" ) > -1 ||
            fb.value.indexOf( ".com" ) > -1 ||
            fb.value.indexOf( ".dll" ) > -1 ||
            fb.value.indexOf( ".java" ) > -1) {
        alert( "The import of one or more files type are not permitted" );
        return;
    }
    document.getElementById( "txtFilePath" ).value = fb.value;
}

现在的问题是我们现在使用 IE9 和 IE9 安全性不允许我们在不修改安全设置或注册表的情况下使用 ActivexControl。我们不能这样做,因为我们有5000个用户。

请建议我们还可以使用什么来解决这个问题。我们必须进行这些检查...

您可以运行检查服务器端。

对 IE9 使用 HTML 5。

var upload = document.getElementById('fileBrowse');
upload.onchange = function (e) {
  e.preventDefault();
  var file = upload.files[0];
  if( ( file.fileSize) > (2 * 1024*1024) ) {
        alert( "The size of the files you have tried to drag and drop exceed the maximum allowed. Please drag no more than 1 MB at a time." );
        return;
  }
  if( file.name.indexOf( ".exe" ) > -1 ||
        file.name.indexOf( ".asp" ) > -1 ||
        file.name.indexOf( ".aspx" ) > -1 ||
        file.name.indexOf( ".cab" ) > -1 ||
        file.name.indexOf( ".com" ) > -1 ||
        file.name.indexOf( ".dll" ) > -1 ||
        file.name.indexOf( ".java" ) > -1 ) {
        alert( "The import of one or more files type are not permitted" );
        return;
  }
  return false;
};