Php 通过表单上传简单图像:如何处理错误
这是一个上传图像的简单表单。一个问题是,指向upload_file.php的操作完成了所有工作。如果抛出错误,如何捕获此错误以向用户显示 (示例取自) 从表单中,我需要能够执行类似的操作(在伪代码中)Php 通过表单上传简单图像:如何处理错误,php,html,Php,Html,这是一个上传图像的简单表单。一个问题是,指向upload_file.php的操作完成了所有工作。如果抛出错误,如何捕获此错误以向用户显示 (示例取自) 从表单中,我需要能够执行类似的操作(在伪代码中) 参考查看$\u文件-尝试此教程,谢谢sundar,但文件上载解决方案会简单地重定向错误。我需要捕获错误并直接报告到正在上载的同一页面。例如,用户看到错误“无法上载PNG文件”。 <html> <body> <form action="upload_file.php"
参考查看$\u文件-尝试此教程,谢谢sundar,但文件上载解决方案会简单地重定向错误。我需要捕获错误并直接报告到正在上载的同一页面。例如,用户看到错误“无法上载PNG文件”。
<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>
echo json_encode(array("error" => $error, "error_desc" => $error_desc, "images" => $images));
if ($error) {
$("#div_error").html("Sorry there was an error " . $error_desc);
}
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']`