2017-07-07 53 views
-1

我要上傳與jQuery或PHP之前驗證我的圖像大小,高度,寬度和圖像格式。我找到了很多答案,但我沒有發現所有的驗證都在一起。上傳的PHP的jQuery之前如何驗證圖像尺寸,高度,寬度和格式?

圖像格式= PNG,圖像尺寸= 2MB,圖像高度= 800像素,圖像寬度= 600

+0

http://php.net/manual/en/features.file-upload.post-method.php和PHP的任何imagelib的組合應該訣竅 –

+1

請添加您嘗試過的代碼 –

+1

@ Ann-SophieAngermüller否。問題是要求在上傳之前驗證文件*。這可以幫助:https://stackoverflow.com/questions/12570834/how-to-preview-image-get-file-size-image-height-and-width-before-upload –

回答

2

可以使用jQuery來實現這一點。

演示代碼 一旦寫一個正常代碼輸入類型=「文件」,並且在下面的jQuery寫下他們的ID。

$(document).ready(function(){ 

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

$('#file').change(function() { 
    var file = $(this)[0].files[0]; 

    img = new Image(); 
    var imgwidth = 0; 
    var imgheight = 0; 
    var maxwidth = 640; 
    var maxheight = 640; 

    img.src = _URL.createObjectURL(file); 
    img.onload = function() { 
    imgwidth = this.width; 
    imgheight = this.height; 

    $("#width").text(imgwidth); 
    $("#height").text(imgheight); 
    if(imgwidth <= maxwidth && imgheight <= maxheight){ 

    var formData = new FormData(); 
    formData.append('fileToUpload', $('#file')[0].files[0]); 

    $.ajax({ 
     url: 'upload_image.php', 
     type: 'POST', 
     data: formData, 
     processData: false, 
     contentType: false, 
     dataType: 'json', 
     success: function (response) { 
     if(response.status == 1){ 
      $("#prev_img").attr("src","upload/"+response.returnText); 
      $("#prev_img").show(); 
      $("#response").text("Upload successfully"); 
     }else{ 
      $("#response").text(response.returnText); 
     } 
     } 
    }); 
    }else{ 
    $("#response").text("Image size must be "+maxwidth+"X"+maxheight); 
    } 
}; 
img.onerror = function() { 

    $("#response").text("not a valid file: " + file.type); 
} 

}); 
}); 
1

正如您所要求的jQuery或PHP,我會建議你使用PHP這種驗證,由於視圖必須在服務器端驗證上傳文件的安全點。 首先要檢查,如果文件是圖像,你可以使用

mime_content_type or finfo_open() 

驗證您的文件後的圖像,你可以去寬度和高度

list($width, $height) = getimagesize($_FILES["fileToUpload"]); 

尺寸爲您使用

$_FILES["fileToUpload"]["size"] 

希望結合這將解決您的問題。

相關問題