2012-09-10 7 views
1

jquery를 사용하여 이미지 업로드 포럼의 유효성을 검사하고 게시하는 방법을 알고 싶습니다. 제목과 이미지의 두 가지 입력 만 있습니다. 이 필드 중 하나라도 비어 있거나 업로드 된 파일의 형식이 잘못된 경우 오류를 제공해야합니다. 여기에 당신이 jQuery를 사용하여 파일을 확인할 수 없습니다 코드 I (이 순간에 jQuery를 사용하지 않습니다.)이jQuery를 사용하여 유효성을 검사하고 게시하십시오.

Image.php

<?php 

$uploadDir = 'images/'; //Image Upload Folder 
if(isset($_POST['Submit'])) 
{ 
    $title = mysql_real_escape_string($_POST['title']); 
    $fileName = $_FILES['Photo']['name']; 
    $tmpName = $_FILES['Photo']['tmp_name']; 
    $fileSize = $_FILES['Photo']['size']; 
    $fileType = $_FILES['Photo']['type']; 
    $filePath = $uploadDir . $fileName; 
    $result = move_uploaded_file($tmpName, $filePath); 
    if (!$result) { 
     echo "Error uploading file"; 
     exit; 
    } 
    if(!get_magic_quotes_gpc()) 
    { 
     $fileName = addslashes($fileName); 
     $filePath = addslashes($filePath); 
    } 
    $query = "INSERT INTO images(title,image) VALUES ('".$title."','".$filePath."')"; 
    mysql_query($query) or die (mysql_error()); 
} 
?> 

<form name="Image" enctype="multipart/form-data" action="image.php" method="POST"> 
<input type="text" name="title" id="title" value=""><br/><br/> 
<input type="file" name="Photo" size="20" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png"><br/> 
<INPUT type="submit" class="button" name="Submit" value=" Submit "> 
</form> 

답변

0

입니다, 당신은 올바른 확장자를 가지고 있음을 확인할 수 있습니다 . 필드가 비어 있는지 확인하려면 다음을 사용할 수 있습니다

var extension = $('input[name=Photo]').val().split('.').pop(); 
if (extension !== "gif" && extension !== "jpg") { 
    // error code 
} 

난 당신이 파일을 게시 할 수 AJAX를 사용하려면 확실하지 않다 :

if ($('#title').val() === '') { 
    // error code 
} 

당신은 같은과 파일 확장자를 확인할 수 있습니다 ,하지만 당신은 할 필요가 없습니다. 양식 제출 이벤트에 대한 유효성 검증을 첨부하면 오류가있는 경우 양식 제출을 중지 할 수 있으며, 그렇지 않으면 양식을 서버에 제출하게 할 수 있습니다. 당신은 확장에 확인할 수

$('form').submit(function() { 
    var error = false; 
    // error checking here 

    if (error) { 
     return false; 
    } 
}); 
+0

감사합니다. jpg 및 gif처럼 –

+0

gif 또는 jpg를 확인하도록 코드를 업데이트했습니다. –

0

...

$('form').submit(function(event) { 
    var file = $('input[type=file]').val();  

    if (! file) { 
     alert('The file is required.'); 
     event.preventDefault(); 
     return; 
    } 

    if (file.match(/\.(?:jpeg|jpg|gif)$/)) { 
     alert('Image files only!'); 
     event.preventDefault(); 
    } 

}); 

... 또는 당신은 MIME 타입에 확인할 수 있습니다.

$('form').submit(function(event) { 
    var file = $('input[type=file]').prop('files')[0]; 

    if (! file) { 
     alert('The file is required.'); 
     event.preventDefault(); 
     return; 
    } 

    var mime = file.type; 

    if (mime != 'text/jpeg' || mime != 'application/gif') { 
     alert('Image only!'); 
     event.preventDefault(); 
    } 

}); 

은 물론, 당신도 서버의 유효성을 검사 할 필요가,이 코드는 자바 스크립트 사용이 가능한 사용자 그냥 의례이다.

관련 문제