簡體   English   中英

使用jQuery驗證檢查圖像大小不起作用

[英]Checking Image size using jQuery validation not working

我正在將圖像上傳到文件夾,但是在上傳之前,我正在檢查圖像的擴展名和大小。 我正在使用jQuery驗證。

在上載問題之前,我檢查了SO,然后找到了代碼。 但是問題是當我上傳的圖像小於100kb(實際圖像大小為98kb)時,出現錯誤"File size must be less than 5" 我嘗試了另一張3.8MB的圖像,但仍然收到相同的錯誤。

您能幫我在這里使用多少尺寸的圖像? 什么是文件大小:5?

誰能幫我解決這個問題?

 $.validator.addMethod('filesize', function(value, element, param) { return this.optional(element) || (element.files[0].size <= param) }, 'File size must be less than {0}'); $(function($) { "use strict"; $('#form').validate({ rules: { image: { //required: true, extension: "jpg,jpeg,png", filesize: 5, } }, }); }); 
 <form id="form" method="post" action=""> <input type="file" name="image" /> <input type="submit" value="Upload" /> </form> <script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script> 

您的參數僅設置為5

$('#form').validate({
    rules: {
      image: {
        ....
        filesize: 5,  ...

那是5 BYTES ,所以對於任何大小為98 kB或3.8 MB的文件,您當然都會收到錯誤消息。 由於它們都大於5個字節,因此它們將使您的自定義規則失敗,該規則僅允許小於 5個字節的文件。

如果要允許文件小於5 MB,請嘗試5242880

filesize: 5242880 // <- 5 MB

 $.validator.addMethod('filesize', function(value, element, param) { return this.optional(element) || (element.files[0].size <= param) }, 'File size must be less than {0} bytes'); $(function($) { "use strict"; $('#form').validate({ rules: { image: { //required: true, extension: "jpg,jpeg,png", filesize: 5242880 // <- 5 MB } }, }); }); 
 <form id="form" method="post" action=""> <input type="file" name="image" /> <input type="submit" value="Upload" /> </form> <script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script> 

通常,在這些類型中,文件大小以字節為單位指定。 因此,您必須將其乘以1024乘數。 例如,如果您要檢查文件大小是否小於5MB,則應使用

image: {
  extension: "jpg,jpeg,png",
  filesize: 5*1024*1024,
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM