现在的位置: 首页 > 综合 > 正文

JS 获取上传文件大小的方法

2018年05月22日 ⁄ 综合 ⁄ 共 1449字 ⁄ 字号 评论关闭
第一种方法
function getFileSize(filePath)   
{   
    var fso = new ActiveXObject("Scripting.FileSystemObject");   
    alert("文件大小为:"+fso.GetFile(filePath).size);   
}   
</script>   
<body>   
<INPUT TYPE="file" NAME="file" SIZE="30" onchange="getFileSize(this.value);">   
</body>  

第二种方法
<script type="text/javascript">   
function getFileSize(filePath)   
{   
    var image = new Image();   
    image.dynsrc = filePath;   
    alert(image.fileSize);   
}   
</script>   
<body>   
<INPUT TYPE="file" NAME="file" SIZE="30" onchange="getFileSize(this.value)">   
</body>  

第一种方法会报“Automation” 的错误。在IE8下载需要允许运行。

第二种方法在IE6下面可以,在IE8下面会报"无法设置dynsrc属性.拒绝访问.“错误,如果用大写的DYNSRC,就不会报错,但是后面的fileSize就不能用了。

相关文章:http://www.csharpwin.com/dotnetspace/12652r1167.shtml

原文地址:http://hi.baidu.com/_feiying/blog/item/dac89227fc52a008908f9d0e.html/cmtid/78efc59bb20d36bbc8eaf445

限制:<input type="text" size="4" value="10" name="fileSizeLimit" id="fileSizeLimit"/> K
<input type="file" name="file1" id="file1" size="40" onchange="changeSrc(this)"/>
<br>
<img src=http://blog.xunuo.com/blog/images/icons/23.gif id="fileChecker" alt="test"/>

<script type="text/javascript">
var oFileChecker = document.getElementById("fileChecker");

function changeSrc(filePicker)
{
    oFileChecker.src = filePicker.value;
}

oFileChecker.onreadystatechange = function ()
{
    if (oFileChecker.readyState == "complete")
    {
        checkSize();
    }
}

function checkSize()
{
    var limit  = document.getElementById("fileSizeLimit").value * 1024;

    if (oFileChecker.fileSize > limit)
    {
        alert("too large");
    }
    else
    {
        alert("ok");
    }
}
</script>  

上面方法有其可取之处

相关文章:http://www.csharpwin.com/dotnetspace/12652r1167.shtml

抱歉!评论已关闭.