In my ASP website I have a form with some textbox, a file upload control and submit form option. I want to avoid users from attaching 0 KB file. I can get the size in my vb code in the background. But how can I get file size and avoid the users from attaching it. I want to give a validation message to the user if they attach a 0 kb file. How it can be done?
            Asked
            
        
        
            Active
            
        
            Viewed 796 times
        
    2 Answers
2
            
            
        Answered here: StackOverflow question
Use Javascript to validate a files size before upload. Can be achieved using the File API included in most modern browsers.
var input = document.getElementById('file');
if(input.files[0].size<1000) alert('Please make the file at least 1kb!');
 
    
    
        Community
        
- 1
- 1
 
    
    
        James Hunt
        
- 2,448
- 11
- 23
- 
                    It does not work in IE8 gives error Error: 'files.0' is null or not an object . But works in chrome – IT researcher Jul 02 '14 at 08:04
- 
                    Polyfill for backwards compatibility of File API - https://github.com/Jahdrien/FileReader – James Hunt Jul 02 '14 at 08:18
0
            
            
        You can do it on client side, as given:
function GetFileSize(fileid) {
    try {
        var fileSize = 0;
        //for IE
        if ($.browser.msie) {
            //before making an object of ActiveXObject, 
            //please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in kb
            fileSize = fileSize / 1048576; //size in mb 
        }
            //for FF, Safari, Opeara and Others
        else {
            fileSize = $("#" + fileid)[0].files[0].size //It will calculate file size in kb
             // Put Your Alert or Validation Message Here
        }
    }
    catch (e) {
        alert("Error is :" + e);
    }
}
 
    
    
        Pawan
        
- 1,704
- 1
- 16
- 37
- 
                    ok. But answer from James Hunt appears easy and simple. Is there any disadvantage in using that method? – IT researcher Jul 02 '14 at 08:01
- 
                    
- 
                    The above code also didn't work in IE 8. Because `filePath` will be set to fake path(like C:\fakepath\New Text Document.txt instead of real path of file), not the actual path. so objFile.size; command files and gives error like file not found – IT researcher Jul 02 '14 at 12:53
