开发者

Javascript to check filesize before upload in Internet Explorer

开发者 https://www.devze.com 2023-04-01 05:48 出处:网络
Is it possible to use Javascript to check for a file\'s size (at the client side) before it is actually uploaded to the server?

Is it possible to use Javascript to check for a file's size (at the client side) before it is actually uploaded to the server?

The application is built on EXTJS and Java and is restricted to usage by Internet 开发者_JAVA百科Explorere 7 on Windows XP machines. No usage of activeX is allowed.

The workflow is as such: User selects a file to upload. Validation kicks in immediately to check for file type and filesize. If filesize exceeds limit, the GUI will prompt with error. If filesize is within the limit, the full filepath will be passed to the server end (java servlet) to be uploaded.

Is the filesize check and reading of full file path possible to be achieved with javascript?


It is possible with ActiveX Objects.

<html>
<head>
<script>
function getSize()
{
    var myFSO = new ActiveXObject("Scripting.FileSystemObject");
    var filepath = document.upload.file.value;
    var thefile = myFSO.getFile(filepath);
    var size = thefile.size;
    alert(size + " bytes");
}
</script>
</head>
<body>
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onClick="getSize();">
</form>
</body>
</html>


There's currently no way to portably check the size of an uploaded file from the web browser. The HTML5 File API makes this possible, but that's not available in MSIE7 -- it's currently on track for MSIE10.

There is intentionally no way to determine the full path of an uploaded file, as that may include sensitive information, like the name of the end user.


The reason you can't is because it would be bad if browsers, and javascript, could access the clients filesystem.

This is actively denied and can be seen as an attack.

Using jQuery, Restricting File Size Before Uploading


Please try below code,

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(function() {
$("document").ready(function(){
        $("#myFile1").change(function() {

        var f1=document.getElementById("myFile1").value;
        if((f.size||f.fileSize)==09765625)
        {
        alert("file size is less than 1mb");
        }
        else
        {
        alert("file size should not exceed more than 1mb");
                $(this).val($.data(this, 'f'));
        return false;
        }

            });
});
})
</script>
</head>
<body>

<input type='file' name="file" id="myFile1" />

</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消