JavaScript file upload size validation

后端 未结 13 2160
眼角桃花
眼角桃花 2020-11-22 00:23

Is there any way to check file size before uploading it using JavaScript?

13条回答
  •  渐次进展
    2020-11-22 01:02

    I use one main Javascript function that I had found at Mozilla Developer Network site https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications, along with another function with AJAX and changed according to my needs. It receives a document element id regarding the place in my html code where I want to write the file size.

    
    
    function updateSize(elementId) {
        var nBytes = 0,
        oFiles = document.getElementById(elementId).files,
        nFiles = oFiles.length;
    
        for (var nFileId = 0; nFileId < nFiles; nFileId++) {
            nBytes += oFiles[nFileId].size;
        }
        var sOutput = nBytes + " bytes";
        // optional code for multiples approximation
        for (var aMultiples = ["K", "M", "G", "T", "P", "E", "Z", "Y"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
            sOutput = " (" + nApprox.toFixed(3) + aMultiples[nMultiple] + ")";
        }
    
        return sOutput;
    }
    
    
    
    
    
    
    
    document.getElementById('spanFileSizeText').innerHTML=updateSize("inputFileUpload");
    
    

    Cheers

提交回复
热议问题