jQuery从函数内部检查文件大小

时间:2018-09-14 09:41:36

标签: javascript jquery

所以我有这些Jquery代码,该函数将在其中检查文件扩展名和输入文件中的文件大小。检查文件扩展名可以正常工作,但文件大小检查不起作用,你们可以帮助我解决这个问题吗?

$(document).ready(function () {
/* Some other code 

*/

var fileExtension = ['jpeg', 'jpg', 'png', 'pdf'];    
    var status = false;

    function checkFile(fileinput){
        if ($.inArray(fileinput.split('.').pop().toLowerCase(), fileExtension) == -1) {
            alert("Tolong upload file dengan extensi: " + fileExtension.join(', '));
            fileinput.value = "";
            return status = false;
        }

        if (fileinput[0].size > 1048576) {
            alert("The maximum file size is 1 mb");
            fileinput.value = "";
            return status = false;
        }

        else {
            return status = true;
        }
    }

    $('#btn_IdentitasKTP\\/Paspor').on('click', function () {
        $('#file_IdentitasKTP\\/Paspor').trigger('click')
    });

    $('#file_IdentitasKTP\\/Paspor').change(function () {

        var fileinput = $('#file_IdentitasKTP\\/Paspor').val();

        checkFile(fileinput);

        if (status == true) {
            var file_name = this.value.replace(/\\/g, '/').replace(/.*\//, '');
            $('#text_IdentitasKTP\\/Paspor').val(file_name);
            status = false;
        }

    });
});

1 个答案:

答案 0 :(得分:0)

例如通过AJAX上传图像。您只需编写此代码。您将根据对象调整大小。它将返回该对象的大小。

$(document).ready(function(e) {
  $("#uploadimage").on('submit', (function(e) {
    e.preventDefault();
    formdata = new FormData(this);
    if (formdata[0].size = < 1000) {
      $.ajax({
        url: "PHp File name path", // Url to which the request is send
        type: "POST", // Type of request to be send, called as method
        data: formdata, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false, // The content type used when sending data to the server.
        cache: false, // To unable request pages to be cached
        processData: false, // To send DOMDocument or non processed data file it is set to false
        success: function(data) // A function to be called if request succeeds
        {
          $('#loading').hide();
          $("#message").html(data);
        }

      });
    } else {
      alert("You can not Upload this file Please resize this image.")
    }
  }));