0

I need to prevent user from uploading large image to server and wanted to use the simple input type="file". Using the jQuery below, how do I reset the "input file" when this.files exceed 1048000?

$('.image-file').bind('change', function() {
  if ( this.files[0].size > 1048000 ) {
    alert('Image size can not more than 1Mb.');
    // going to reset the file            
  }
});

<input type="file" name="photo[]" class="image-file">
<input type="file" name="photo[]" class="image-file">
<input type="file" name="photo[]" class="image-file">
4

1 回答 1

3

Please try the following code. But to get the file size you can use server side code which will return the size of the file..

$('#form_id').each(function(){
    this.reset();
});


<input id="fileInput" type="file" onchange="AlertFilesize();" />


Following code is to get the file size using javascript function.

function AlertFilesize(){
if(window.ActiveXObject){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var filepath = document.getElementById('fileInput').value;
    var thefile = fso.getFile(filepath);
    var sizeinbytes = thefile.size;
}else{
    var sizeinbytes = document.getElementById('fileInput').files[0].size;
}

var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}

alert((Math.round(fSize*100)/100)+' '+fSExt[i]);

}

于 2013-07-26T03:11:15.980 回答