For Web developers, file uploading is common and it is essential to determine the file size. Here we mainly introduce several common methods for JavaScript to determine the file size.
The first method is to apply ActiveX controls, for example:
JavaScript code
- <SCRIPT type = "text/JavaScript">
- Function getfilesize (filepath)
- {
- VaR FSO = new activexobject ("scripting. FileSystemObject ");
- Alert ("file size:" + 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 FSO = new activexobject ("scripting. fileSystemObject "); alert (" file size: "+ FSO. getFile (filepath ). size) ;}</SCRIPT> <body> <input type = "file" name = "file" size = "30" onchange = "getfilesize (this. value); "> </body>
This method can be implemented and easily thought by developers, but the only drawback is that there is a security prompt. Of course, change the file name. HTA will block the security prompt, but it is difficult to obtain it.Not recommended, not to mention
Next we will talk about another method. There is an IMG tag in HTML tags that is not "deep" for general developers. let's first talk about its attributes:SRC, DYNSRC, start, ALT, controls, loop, loopdelay, heatace, vspace ....Some common attributes will not be listed. Here we will talk about the "DYNSRC" attribute: DYNSRC can be used to insert various multimedia, the format can be WAV, Avi, AIFF, AU, MP3, Ra, ram, and so on. The URL is an audio or video file and its path, which can be a relative or absolute path.
Example:
In this way, the path of any type of file can be dynamically assigned based on DYNSRC, and the file size can be obtained in Javascript Based on The filesize attribute of the image object. Of course, the image object has several other attributes, such:Filecreateddate, filemodifieddate, filesize, fileupdateddate, filters...The Code is as follows:
JavaScript code
- <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>
<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>
After testing, no security prompt is displayed for the file size,Recommendation, not to mention
From: http://kokobox.javaeye.com/blog/227071