简体   繁体   English

防止使用 Javascript (JQuery) 更改文件输入

[英]Prevent file input from changing with Javascript (JQuery)

I'm trying to prevent a file input being changed if I conditionally tell the user the file is too large, but even capturing the change and preventing default, it's still filled in ie:如果我有条件地告诉用户文件太大,我试图防止文件输入被更改,但即使捕获更改并防止默认,它仍然被填充,即:

  // CHECK FILE ISNT ABOVE 500MB ON CHANGE
      $(".upload-file").change(function (e) {

        // conditional checks
        var fileSize = $('.upload-file').get(0).files[0].size; // in bytes

        if (fileSize > 500000000) {
          e.preventDefault();
          swal('File size is more than 500 MB, please upload a smaller file. Support for larger files will be rolled out soon.');
          return false;
        }

  

      });

Here's my code, what am I doing wrong?这是我的代码,我做错了什么?

如果要重置文件输入:

$(".upload-file").val(null);

I would suggest to reset the input type=file if the condition doesn't match as below:如果条件不匹配,我建议重置输入 type=file 如下:

$('.upload-file').on("change", function (e) {
    if (this.files[0] != null) {
        var fileSize = this.files[0].size;
        if (fileSize > 50) {
            alert("File too large!");
            var control=$("#"+$(this).attr('id'));//get the id
            control.replaceWith(control = control.clone().val(''));//replace with clone
            return;
        }
        else {
            alert("File ok");
        }
    }
});

Also do note that this.files[0].size returns file size in bytes.还要注意 this.files[0].size 以字节为单位返回文件大小。 So according to your validation, you will not allow to upload file whose size is more that 50 bytes因此,根据您的验证,您将不允许上传大小超过 50 字节的文件

The code below will check the file size, if it is above your threshold (maxFileSize ), then it will throw an error and reset the file upload dialogue.下面的代码将检查文件大小,如果它高于您的阈值 (maxFileSize),则会抛出错误并重置文件上传对话框。 This prevents any further processing of the file, for example if you are manipulating the file in some way before submitting the form.这可以防止对文件进行任何进一步处理,例如,如果您在提交表单之前以某种方式操作文件。

 $(document).ready(function() { $('.upload-file').on('change', function(e) { try { var fileSize = 0; var maxFileSize = 5 // in mb fileSize = $('.upload-file')[0].files[0].size //size in kb fileSize = fileSize / 1048576; //size in mb if (fileSize > maxFileSize) throw "Too big"; } catch (e) { alert("Sorry, file is too large. Please select one that is smaller than "+maxFileSize +' Mb'); $('.upload-file').val(null); } }); });

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

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