Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a file's upload size using simple Javascript?

I have upload file functionality on one of the page. I check for the extension of the file using JavaScript. Now i want to restrict the user from uploading file greater than 1 MB. Is there any way i can check the file upload size using JavaScript.

My code currently look like this:

<script language="JavaScript">
function validate() {
   var filename = document.getElementById("txtChooseFile").value;
   var ext = getExt(filename);
   if(ext == "txt" || ext == "csv")
      return true;
   alert("Please upload Text files only.");
   return false;
}

function getExt(filename) {
   var dot_pos = filename.lastIndexOf(".");
   if(dot_pos == -1)
      return "";
   return filename.substr(dot_pos+1).toLowerCase();
}
</script>
like image 666
Pankaj Khurana Avatar asked Oct 22 '09 12:10

Pankaj Khurana


2 Answers

See http://www.w3.org/TR/FileAPI/. It is supported by Firefox 3.6; I don't know about any other browsers.

Within the onchange event of a <input id="fileInput" type="file" /> simply:

var fi = document.getElementById('fileInput');
alert(fi.files[0].size); // maybe fileSize, I forget

You can also return the contents of the file as a string, and so forth. But again, this may only work with Firefox 3.6.

like image 163
Matthew Avatar answered Oct 17 '22 10:10

Matthew


Now it is possible to get file size using pure JavaScript. Nearly all browser support FileReader, which you can use to read file size as well as you can show image without uploading file to server. link

Code:

    var oFile = document.getElementById("file-input").files[0]; // input box with type file;
    var img = document.getElementById("imgtag");
    var reader = new FileReader();
    reader.onload = function (e) {
            console.log(e.total); // file size 
            img.src =  e.target.result; // putting file in dom without server upload.

   };
   reader.readAsDataURL(oFile );

You can get file size directly from file object using following code.

 var fileSize = oFile.size;
like image 29
Anoop Avatar answered Oct 17 '22 10:10

Anoop