JavaScript 文件上传大小验证 [英] JavaScript file upload size validation

查看:24
本文介绍了JavaScript 文件上传大小验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在使用 JavaScript 上传之前检查文件大小?

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

推荐答案

,您可以使用文件 API 用于此.

Yes, you can use the File API for this.

这是一个完整的例子(见评论):

Here's a complete example (see comments):

document.getElementById("btnLoad").addEventListener("click", function showFileSize() {
    // (Can't use `typeof FileReader === "function"` because apparently it
    // comes back as "object" on some browsers. So just see if it's there
    // at all.)
    if (!window.FileReader) { // This is VERY unlikely, browser support is near-universal
        console.log("The file API isn't supported on this browser yet.");
        return;
    }

    var input = document.getElementById('fileinput');
    if (!input.files) { // This is VERY unlikely, browser support is near-universal
        console.error("This browser doesn't seem to support the `files` property of file inputs.");
    } else if (!input.files[0]) {
        addPara("Please select a file before clicking 'Load'");
    } else {
        var file = input.files[0];
        addPara("File " + file.name + " is " + file.size + " bytes in size");
    }
});

function addPara(text) {
    var p = document.createElement("p");
    p.textContent = text;
    document.body.appendChild(p);
}

body {
    font-family: sans-serif;
}

<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load'>
</form>

有点跑题,但是:请注意,客户端验证不可替代服务器端验证.客户端验证纯粹是为了提供更好的用户体验.例如,如果您不允许上传超过 5MB 的文件,您可以使用客户端验证来检查用户选择的文件大小是否不超过 5MB,如果是,则给他们一个友好的消息(因此他们不会花费所有时间上传只是为了将结果扔到服务器上),但是您必须在服务器上强制执行该限制,因为所有客户端限制(和其他验证)可以规避.

Slightly off-topic, but: Note that client-side validation is no substitute for server-side validation. Client-side validation is purely to make it possible to provide a nicer user experience. For instance, if you don't allow uploading a file more than 5MB, you could use client-side validation to check that the file the user has chosen isn't more than 5MB in size and give them a nice friendly message if it is (so they don't spend all that time uploading only to get the result thrown away at the server), but you must also enforce that limit at the server, as all client-side limits (and other validations) can be circumvented.

这篇关于JavaScript 文件上传大小验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆