验证上传文件大小

时间:2016-09-21 05:53:19

标签: javascript jquery model-view-controller

我想查看文件大小,即如果大小超过,则会提示UploadSizeError消息。方法是CheckValidate()。

 var dialogButtons = [
      {
        text: "Upload",
        id: "tpApplicationFormDialog_btnSave",
        disabled: "disabled",
        class: "requiredAtt1",
        click: savetpApplicationFormDialog
      },

HTML

<button type="button" id="tpApplicationFormDialog_btnSave" class="requiredAtt1 ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text">Upload</span></button>
<span class="ui-button-text">Upload</span>

方式

 function CheckValidate() {
        var o = getOptions();
        var f = this.files

        var ret = false;
        if (f.size> 1 || f.fileSize > 1)
        {
            ret = true;
        }
        return ret;
        }

响应

function savetpApplicationFormDialog() {
      if (hasChanges()) {
          commonDialogs.showConfirm(ProjectMessages.ConfirmUpload, function () {
              if(CheckValidate()) {
                  commonDialogs.showProgress(ProjectMessages.UploadSizeError);
              }
                  try {
            commonDialogs.showProgress(ProjectMessages.ProgressUpload);
            var o = getOptions();
            var form = $(o.form);
            form.ajaxSubmit(handleResponse);
          } catch (e) {
            commonDialogs.showError();
          }
        });
      }
    };

2 个答案:

答案 0 :(得分:1)

试试这个

function CheckValidate() {
        var o = getOptions();
        //var f = this.files
         var f=  $("#idoffileinput").get(0).files[0]['size'] //will give file size in bytes
        var ret = false;
        var maxSize = xxx ;//max size in bytes
        if (f> maxSize )
        {
            ret = true;
        }
        return ret;
        }

答案 1 :(得分:0)

JSBin:http://jsbin.com/lezilu/edit?js,output

JS

let input = document.querySelector(".file");
let show = document.querySelector(".show");

input.addEventListener("change", e => {

    let file = e.target.files[0];
    let fileName = file.name;
    let fileSize = file.size;

    if(fileSize < 1000){

        // Less then 1MB

        show.textContent = "Pass";


    }else{

        // Bigger then 1 MB
        show.textContent = "Chose again";

    }



});