【问题标题】:alert then reload page IN detect file extension upload script警报然后重新加载页面 IN 检测文件扩展名上传脚本
【发布时间】:2012-11-06 22:45:00
【问题描述】:

我在上传时使用这个 javascript 来限制文件类型的扩展名:

function TestFileType( fileName, fileTypes ) {
if (!fileName) return;

dots = fileName.split(".")
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];

return (fileTypes.join(".").indexOf(fileType) != -1) ?
alert('Correct File Type Function Here') :
alert('Wrong File Type Function Here');
}

与

<input name="replay_file" id="replay_file" type="file"/> 
<input type="submit" id="upload_file" value="Upload" name="uploadReplay" onClick="TestFileType(this.form.replay_file.value, ['w3g','.w3g']);" />

我希望它发出警报(错误的文件类型)然后重新加载页面(这样它会取消上传而不是浪费时间)但到目前为止我只能让警报框工作但不能让页面重新加载功能之后也就是说,页面重新加载不起作用我什至尝试了 goto url 和 windows 位置,但它不起作用,只会在警告框后继续上传文件:

return (fileTypes.join(".").indexOf(fileType) != -1) ?
null() :
alert('Warcraft III replay file (.w3g) allowed only!');window.location.reload();
}

我是否遗漏了什么,或者在文件上传时它不会以这种方式工作?

【问题讨论】:

    标签: javascript html upload reload


    【解决方案1】:

    使用onsubmit事件取消表单,以防扩展名不正确,如下所示:

    function TestFileType( fileName, fileTypes ) {
    if (!fileName) return;
    
    dots = fileName.split(".")
    //get the part AFTER the LAST period.
    fileType = "." + dots[dots.length-1];
    
    if (fileTypes.join(".").indexOf(fileType) != -1) {
       //alert('Correct File Type Function Here');
       return true;
    } else {
       alert('Wrong File Type Function Here');
       return false;
    }
    }
    

    在您的表单元素上连接onsubmit 事件:

    <form onsubmit="return TestFileType(this.form.replay_file.value, ['w3g','.w3g']);" ...
    

    【讨论】:

    • onSubmit 根本不起作用,但它适用于 onClick.. 谢谢!
    【解决方案2】:

    杰里米,

    我看到您已经接受了这个问题的答案,但由于您发布的代码中存在基本问题,我担心您将来会遇到其他问题。

    首先,

    return (condition) ? alert('Correct') : alert('Wrong');
    

    alert 是一个没有返回值的本地函数。 如果您确实将其视为返回某些内容,则该内容将是未定义的,因此无论您的条件是什么,上面的行总是返回 undefined。 如果我的解释不清楚,请试试这个:

    alert(alert(Math.min(-3,5)));
    

    其次,

    return (condition) ? null() : alert('msg'); window.location.reload();
    

    null 不是函数。它是一个保留字,表示具有未知值的已定义对象。

    此外,三元 if ( b ? x : y ) 以第一个分号结束,因此永远不会调用 reload()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 2019-07-24
      相关资源
      最近更新 更多