通过表单上传简单图像:如何处理错误

时间:2014-02-21 06:05:47

标签: php html

这是上传图片的简单表格。一个问题,指向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);
}

1 个答案:

答案 0 :(得分: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']`

来自http://davidwalsh.name/basic-file-uploading-php

的参考资料