简体   繁体   English

文件输入:Chrome在提交表单之前不会检查文件是否仍然存在

[英]File input : Chrome is not checking if file still exist before submitting form

I recently found a bug that made my server crash during a file upload. 我最近发现了一个错误,该错误使文件上传期间服务器崩溃。

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. 如果用户在提交表单之前删除或重命名了文件,Chrome仍然会发送一个空文件。 (while firefox and IE handle the error correctly) (而Firefox和IE则正确处理了该错误)

After the user has clicked on the "submit" button, I've tryed to check the file size, but it is not null. 用户单击“提交”按钮后,我尝试检查文件大小,但它不为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. 我已经处理了错误的服务器端,但想添加一些验证客户端。

Using the JavaScript File API we can pull the size of the file through the object's size property using element.files[0].size . 使用JavaScript File API,我们可以使用element.files[0].size通过对象的size属性拉出文件的size To ensure that a file exists with JavaScript, we can simply: 要确保文件存在JavaScript,我们可以简单地:

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

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. 我们使用typeof来确保实际上已选择了一个文件(否则将未定义 el.files[0] ),然后如果通过,则检查文件大小是否大于0。

Here's a JSFiddle demo which I've tested in Chrome. 这是我在Chrome中测试过的JSFiddle演示

As an important note, however, you would still need some server-side validation for users with JavaScript disabled. 不过,重要的是,对于禁用JavaScript的用户,您仍然需要一些服务器端验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM