How to get file name when user select a file via <input type=“file” />?

前端 未结 4 1914
你的背包
你的背包 2020-11-27 15:55

I\'ve seen similar questions before,which ends up with no solution,because of security reasons.

But today I see hostmonster has successfully implemented this,when I

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 16:22

    I'll answer this question via Simple Javascript that is supported in all browsers that I have tested so far (IE8 to IE11, Chrome, FF etc).

    Here is the code.

    function GetFileSizeNameAndType()
            {
            var fi = document.getElementById('file'); // GET THE FILE INPUT AS VARIABLE.
    
            var totalFileSize = 0;
    
            // VALIDATE OR CHECK IF ANY FILE IS SELECTED.
            if (fi.files.length > 0)
            {
                // RUN A LOOP TO CHECK EACH SELECTED FILE.
                for (var i = 0; i <= fi.files.length - 1; i++)
                {
                    //ACCESS THE SIZE PROPERTY OF THE ITEM OBJECT IN FILES COLLECTION. IN THIS WAY ALSO GET OTHER PROPERTIES LIKE FILENAME AND FILETYPE
                    var fsize = fi.files.item(i).size;
                    totalFileSize = totalFileSize + fsize;
                    document.getElementById('fp').innerHTML =
                    document.getElementById('fp').innerHTML
                    +
                    '
    ' + 'File Name is ' + fi.files.item(i).name + ' and Size is ' + Math.round((fsize / 1024)) //DEFAULT SIZE IS IN BYTES SO WE DIVIDING BY 1024 TO CONVERT IT IN KB + ' KB and File Type is ' + fi.files.item(i).type + "."; } } document.getElementById('divTotalSize').innerHTML = "Total File(s) Size is " + Math.round(totalFileSize / 1024) + " KB"; }
        

    *Please note that we are displaying filesize in KB (Kilobytes). To get in MB divide it by 1024 * 1024 and so on*.

    It'll perform file outputs like these on selecting

提交回复
热议问题