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

前端 未结 8 740
醉梦人生
醉梦人生 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:16

    It might be possible using a lot of browser-specific code. Take a look at the source of TiddlyWiki, which manages to save itself on the user's hard drive by hooking into Windows Scripting Host (IE), XPCOM (Mozilla), etc.

    0 讨论(0)
  • 2020-12-10 05:17

    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.

    0 讨论(0)
  • 2020-12-10 05:17

    I don't think there is any way of doing that with plain JS from a web page.
    With a browser extension maybe, but from a page javascript cannot access the filesystem for security reasons.

    Flash and Java should have similar restrictions, but maybe they are a bit less strict.

    0 讨论(0)
  • 2020-12-10 05:32

    Other that aquiring the filename there is no way for you to find out any other details about the file in javascript including its size.

    Instead you should configure server-side script to block an oversized upload.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-10 05:39

    See here:

    http://www.kavoir.com/2009/01/check-for-file-size-with-javascript-before-uploading.html

    As to all the people saying this has to be done server side, they are absolutely spot on it does.

    In my case though the maximum size I will except is 128Mb, if a user tries to upload something that is 130Mb they should not have to wait the 5 minute upload time to find out it is too big so I need to do an additional check before they submit the page for usability sake.

    0 讨论(0)
提交回复
热议问题