如何使用javascript停止文件上传事件 [英] How stop file upload event using javascript

查看:2809
本文介绍了如何使用javascript停止文件上传事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我上传超过5mb的文件或我的文件扩展名不是 .jpg .png <时,我想停止文件上传事件/ code>。我找到了一个代码但是当我尝试上传无效的文件类型时,它只给我提醒我已经上传了错误的文件,但它没有取消该事件。
以下是代码

I want to stop file upload event when i upload the file more than 5mb or if my file extension is not .jpg or .png. I found a code but when i try to upload the invalid file type then it only gives me alerts that i have upload the wrong file but it does not cancel the event. Here is the code

<script>
function checkFile(fieldObj)
{
    var FileName  = fieldObj.value;
    var FileExt = FileName.substr(FileName.lastIndexOf('.')+1);
    var FileSize = fieldObj.files[0].size;
    var FileSizeMB = (FileSize/5485760).toFixed(2);

    if ( (FileExt != "png" && FileExt != "jpg") || FileSize>5485760)
    {
        var error = "File type : "+ FileExt+"\n\n";
        error += "Size: " + FileSizeMB + " MB \n\n";
        error += "Please make sure your file is in png or jpg format and less than 5 MB.\n\n";

        alert(error);
        return false;
    }
    return true;
}
</script>

这里是html代码

 <input type="file"onchange="checkFile(this)"name='sec_2_img'>


推荐答案

您需要清除'sec_2_img'的值。你可以通过在 alert(错误)之后和 fieldObj.value =; 来实现> return false; 。这将从 sec_2_img 中删除​​文件名,并强制用户选择一个新文件名,同时仍显示该消息,以便用户知道该怎么做。

You need to clear the value of 'sec_2_img'. You do this by adding fieldObj.value = ""; after alert(error) and before return false;. This will remove the file name from sec_2_img and force user to select a new one while still showing the message so user knows what to do.

这篇关于如何使用javascript停止文件上传事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆