文件输入:在提交表单之前,Chrome不会检查文件是否仍然存在 [英] File input : Chrome is not checking if file still exist before submitting form

查看:131
本文介绍了文件输入:在提交表单之前,Chrome不会检查文件是否仍然存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现了一个错误,导致我的服务器在文件上传期间崩溃。

I recently found a bug that made my server crash during a file upload.

当用户点击文件输入时,选择要上传的文件。如果用户在提交表单之前删除或重命名该文件,Chrome仍会发送一个空文件。 (虽然firefox和IE正确处理错误)

When the user clicks on a file input, and chooses a file to upload. If the user deletes or renames the file before submitting the form, Chrome still sends an empty file. (while firefox and IE handle the error correctly)

用户点击提交按钮后,我试图检查文件大小,但它是不为空。

After the user has clicked on the "submit" button, I've tryed to check the file size, but it is not null.

        if (file.size == 0) {
            NotificationFactory.AlertMessage({ messageType: "error", message: "File is missing" });
        }

我已经处理了错误服务器端,但想添加一些验证客户端。

I've already handled the error server-side, but would like to add some validation client-side.

推荐答案

使用JavaScript 文件API 我们可以通过对象的 size property 使用 element.files [0] .size 。为了确保JavaScript存在一个文件,我们可以简单地说:

Using the JavaScript File API we can pull the size of the file through the object's size property using element.files[0].size. To ensure that a file exists with JavaScript, we can simply:

if(typeof el.files[0] !== 'undefined' && el.files[0].size > 0) {
    /* Success! */
}

我们使用 typeof 确保实际选择了一个文件( el.files [0] 否则未定义),然后如果通过我们检查文件大小是否大于0.

We use typeof to ensure that a file has actually been selected (el.files[0] will be undefined otherwise), and then if that passes we check that the file size is greater than 0.

这是一个

Here's a JSFiddle demo which I've tested in Chrome.

但是,作为一个重要的注意事项,您仍然需要对用户进行一些服务器端验证。禁用JavaScript。

As an important note, however, you would still need some server-side validation for users with JavaScript disabled.

这篇关于文件输入:在提交表单之前,Chrome不会检查文件是否仍然存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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