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

前端 未结 8 803
醉梦人生
醉梦人生 2020-12-10 04:41

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

8条回答
  •  自闭症患者
    2020-12-10 05:38

    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;
    

提交回复
热议问题