【问题标题】:How to validate file size before uploading? [duplicate]如何在上传前验证文件大小? [复制]
【发布时间】:2011-08-22 11:31:28
【问题描述】:

可能重复:
How can you determine the file size in JavaScript?

GMail 可以选择检查文件大小和提醒而不让页面回发。

我怎样才能自己实现这个功能?

【问题讨论】:

    标签: javascript file-upload


    【解决方案1】:

    使用 HTML5,您可以使用 JavaScript 在客户端实现此目的。这是 jQuery,但它当然也可以正常工作:http://jsfiddle.net/pimvdb/S4mEv/2/。请注意,它并非在所有浏览器中都可用(目前)。

    $('#file').change(function() {
        alert(this.files[0].size + " bytes");
    });
    

    https://developer.mozilla.org/en/DOM/File

    【讨论】:

      【解决方案2】:

      你可以使用Uploadify,它是一个jQuery 插件,使用flash 来检查文件大小并具有其他简洁的功能。 http://www.uploadify.com/documentation/options/sizelimit/

      【讨论】:

        【解决方案3】:

        你可以做那个文件 HTML5 JS File API

        您可以在我的 Web IDE 中测试运行以下代码(但请使用 google chrome 或 FF): http://codesocialist.com/#/?s=bN

        以下代码为您检索文件类型和文件大小:)

        <input type="file" id="files" name="files[]" multiple />
        <output id="list"></output>
        
        // Check for the various File API support.
        if (window.File && window.FileReader && window.FileList && window.Blob) {
        
            // Great success! All the File APIs are supported.
            function handleFileSelect(evt) {
                var files = evt.target.files; // FileList object
        
                // files is a FileList of File objects. List some properties.
                var output = [];
                for (var i = 0, f; f = files[i]; i++) {
                  output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ', f.size, ' bytes </strong></li>');
                }
        
                document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
            }
        
            // Bind Event Listener
            document.getElementById('files').addEventListener('change', handleFileSelect, false);
        
        } else {
            alert('The File APIs are not fully supported in this browser.');
        }
        

        【讨论】:

        • 如果问题是重复的,请标记它们。请不要将您的答案从一个复制粘贴到另一个。编程中的复制和粘贴是不好的,为什么它对编程的答案有好处?
        【解决方案4】:

        Gmail 为此使用了 Flash 应用程序。如果要检查文件大小,则需要在这样的环境中执行此操作; JavaScript 本身并没有实现这一点的机制。

        【讨论】:

        • 结合 HTML5 就可以了。当用户在&lt;input type=file&gt; 中选择文件时,您可以使用onchange 事件并查找所选文件。还包括文件大小。 developer.mozilla.org/en/DOM/File
        • 有趣,很高兴知道。您可以考虑将其添加为替代答案。
        • 曾经看到 hotmail 网站。由.net 开发的总站点,在该站点中,上传文件时会显示与我想要的一样的警告。
        猜你喜欢
        • 1970-01-01
        • 2012-04-12
        • 1970-01-01
        • 1970-01-01
        • 2011-06-24
        • 1970-01-01
        • 2021-03-09
        • 1970-01-01
        • 2011-04-12
        相关资源
        最近更新 更多