JS to get the size of the uploaded file

Source: Internet
Author: User

We sometimes need to determine the file size before uploading the file. There are two methods:Copy to ClipboardReference: [www.bkjia.com] <! Doctype html public "-// w3c // dtd html 4.0 transitional // en">
<Html>
<Body>
<Input type = "file" NAME = "file" SIZE = "30" onchange = "getFileSize (this)">
<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; title = "alert: Click to View Details"
Alert (image. fileSize );
}

Function getFileSize (fileObj)
{
Var image = new Image ();
Image. dynsrc = fileObj. value;
Var size = image. fileSize | fileObj. files [0]. fileSize;
If (size & gt; 100000 ){
Alert (size );
}

}
</Script>
</Html>
However, the above Code has a problem. when dynsrc is assigned a value, you must have the file operation permission. In other words, the Versions later than IE7 do not allow the browser to operate the file to improve security. Therefore, the above Code is not practical.

The following code reads files by calling ActiveX. You must enable some of ActiveX functions.Copy to ClipboardReference: [www.bkjia.com] <! Doctype html public "-// w3c // dtd html 4.0 transitional // en">
<Html>

<Script type = "text/javascript">

Function getFileSize (fileObj ){
If (document. all ){
Window. oldOnError = window. onerror;
Window. onerror = function (err ){
If (err. indexOf ('utomation ')! =-1 ){
Alert ('No access to the file permissions .');
Return true;
}
Else
Return false;
};
Var fso = new ActiveXObject ('scripting. FileSystemObject ');
Var file = fso. GetFile (fileName );
Window. onerror = window. oldOnError;
Return file. Size;
}
}

</Script>
<Body>
<Input type = "file" NAME = "file" SIZE = "30" onchange = "getFileSize (this)">
</Body>
</Html>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.