2014-02-21 43 views
0

這是一個簡單的表格,上傳圖片。一個問題,指向upload_file.php的操作完成所有工作。如果發生錯誤,我如何捕獲此錯誤以將其顯示給用戶?簡單的圖片上傳:如何處理錯誤

(從http://www.w3schools.com/PHP/php_file_upload.asp所採取的示例)

<html> 
<body> 

<form action="upload_file.php" method="post" 
enctype="multipart/form-data"> 
<label for="file">Filename:</label> 
<input type="file" name="file" id="file"><br> 
<input type="submit" name="submit" value="Submit"> 
</form> 

</body> 
</html> 

編輯


我是不是在這個問題不夠清楚。該文件image_upload.php是通過$ _FILES []數組,並有大量的錯誤檢查其作品。這些錯誤被綁定到php中的JSON數組中,並回顯給調用頁面。即

echo json_encode(array("error" => $error, "error_desc" => $error_desc, "images" => $images)); 

從我需要能夠做類似的東西的形式(在僞代碼)

if ($error) { 
$("#div_error").html("Sorry there was an error " . $error_desc); 
} 
+0

採取$ _FILES一看 - HTTP ://in1.php.net/manual/en/reserved.variables.files.php –

+0

試試這個tuotorial http://blog.trofeosolution.com/index.php/blog/file-upload – Sundar

+0

感謝孫大信,但文件上傳解決方案簡單的重定向與錯誤一起。我需要捕獲錯誤並直接上傳到正在上傳的相同頁面。即例如,用戶看到一個錯誤'無法上傳PNG文件'。 – sapatos

回答

0
if($_FILES['photo']['name']) 
{ 
//if no errors... 
if(!$_FILES['photo']['error']) 
{ 
    //now is the time to modify the future file name and validate the file 
    $new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file 
    if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB 
    { 
     $valid_file = false; 
     $message = 'Oops! Your file\'s size is to large.'; 
    } 

    //if the file has passed the test 
    if($valid_file) 
    { 
     //move it to where we want it to be 
     move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name); 
     $message = 'Congratulations! Your file was accepted.'; 
    } 
} 
//if there is an error... 
else 
{ 
    //set that to be the returned message 
    $message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error']; 
} 
} 

//you get the following information for each file: 
$_FILES['field_name']['name'] 
$_FILES['field_name']['size'] 
$_FILES['field_name']['type'] 
$_FILES['field_name']['tmp_name']` 

refrence從http://davidwalsh.name/basic-file-uploading-php