2014-12-05 71 views
2

我想驗證圖像大小和擴展名,然後再上傳圖像。我有圖像擴展的代碼,我想限制圖像的大小。 這裏是圖像擴展代碼:如何在上傳前驗證圖片大小?

function ValidateFileUpload() { 
    var fuData = document.getElementById('fileChooser'); 
    var FileUploadPath = fuData.value; 


    if (FileUploadPath == '') { 
     alert("Please upload an image"); 

    } else { 
     var Extension = FileUploadPath.substring(
       FileUploadPath.lastIndexOf('.') + 1).toLowerCase(); 



if (Extension == "gif" || Extension == "png" || Extension == "bmp" 
       || Extension == "jpeg" || Extension == "jpg") { 


      if (fuData.files && fuData.files[0]) { 
       var reader = new FileReader(); 

       reader.onload = function(e) { 
        $('#blah').attr('src', e.target.result); 
       } 

       reader.readAsDataURL(fuData.files[0]); 
      } 

     } 


    else { 
      alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. "); 

     } 
    } 
} 

HTML代碼

<input type="file" name="image" id="fileChooser" style="height:28px; width:175px;" onchange="return ValidateFileUpload()"> 
+0

我想在上面的代碼中添加圖像尺寸驗證 – stark 2014-12-05 06:17:13

+0

可能重複[如何預覽圖片,上傳前獲取文件大小,圖像高度和寬度?](http://stackoverflow.com/問題/ 12570834 /如何預覽圖像獲取文件大小圖像高度和寬度之前上傳) – 2014-12-05 06:19:05

回答

1
function ValidateFileUpload() { 

var fuData = document.getElementById('fileChooser'); 
var FileUploadPath = fuData.value; 


if (FileUploadPath == '') { 
    alert("Please upload an image"); 

} else { 
    var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase(); 



    if (Extension == "gif" || Extension == "png" || Extension == "bmp" 
       || Extension == "jpeg" || Extension == "jpg") { 


      if (fuData.files && fuData.files[0]) { 

       var size = fuData.files[0].size; 

       if(size > MAX_SIZE){ 
        alert("Maximum file size exceeds"); 
        return; 
       }else{ 
        var reader = new FileReader(); 

        reader.onload = function(e) { 
         $('#blah').attr('src', e.target.result); 
        } 

        reader.readAsDataURL(fuData.files[0]); 
       } 
      } 

    } 


else { 
     alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. "); 
    } 
}} 

MAX_SIZE用戶輸入文件的最大文件大小您允許的。 你可以在我寫的以下博文中找到一個很好的例子。

html5 file uploading example

5

您可以使用此代碼與HTML 5的測試 演示:Demo for this

<input type="file" id="file" /> 

var _URL = window.URL || window.webkitURL; 

$("#file").change(function(e) { 

    var image, file; 

    if ((file = this.files[0])) { 

     image = new Image(); 

     image.onload = function() { 

      alert("The image width is " +this.width + " and image height is " + this.height); 
     }; 

     image.src = _URL.createObjectURL(file); 


    } 

}); 
+0

是否有任何可能的方式來添加圖像大小限制在上述擴展代碼? – stark 2014-12-05 06:34:14