我正在用一个简单的HTML格式的html工作。我正在添加一些字段,包括文件上传。
但我面临一个奇怪的问题。当我上传图片并提交表格时。它提交但是当我不上传图像并提交表格时。它说“不支持的文件格式”
当我不上传文件并提交表单时,我检查了一下。它甚至没有发布表格。只有“不支持的文件格式”行进入页面并且整页空白。
这是我的代码:
<form action="" method="post" enctype="multipart/form-data">
<table class="form-table">
<tr>
<th>Title<font color="#ff0000">*</font></th>
<td><input name="title" type="text" value="<?=$_POST['title']?>" size="40" /></td>
</tr>
<tr>
<th>Image<font color="#ff0000">*</font></th>
<td><input type="file" name="file_name" /></td>
</tr>
<tr>
<th> </th>
<td> Dimensions: <?=$imgwidth?> x <?=$imgheight?> (Max: 2MB) <br />
JPG format is the one recommended.</td>
</tr>
<tr>
<th></th>
<td><input type="submit" name="btnAdd_cat" class="button" value="Add" /></td>
</tr>
</table>
</form>
Php代码:
<?php
if(isset($_POST['btnAdd_cat'])){
$error = "";
$title = addslashes($_POST['title']);
if(empty($title)) $error .= "Please enter title.<br/>";
if(empty($error)){
$sql = "INSERT INTO ".CATEGORIES." (`title`, `status`) VALUES ('$title', '1')";
mysql_query($sql) or die(__LINE__.mysql_error());
$id = $insert_id = mysql_insert_id();
$success = "Successfuly added.<br/>";
$filename = $_FILES['file_name']['name'];
if(!empty($filename)){
$imgext = strtolower(substr($filename, -4));
$img = ereg_replace("[^a-z0-9._]", "",str_replace(" ", "-",str_replace("%20", "-", strtolower($title))));
$filename = "category-".$insert_id."-".$img.$imgext;
$savefile = "../pictures/".$filename;
//upload
if(copy($_FILES['file_name']['tmp_name'], $savefile)){
//echo "....Image uploaded ";
}else{$warning = "Failed to upload image!<br/>";}
chmod("$savefile",0777);
if(resize_picture("$savefile","$savefile","$imgwidth","$imgheight")){
//echo "....Image resized ";
}else{$warning = "Failed to resize image!<br/>";}
$image = $filename;
}
if(mysql_query("UPDATE ".CATEGORIES." SET image='".$image."' WHERE id='".$id."'")){
$success .= "Image added.<br/>";
unset($_GET);
} else {die(__LINE__.mysql_error());}
}
}
?>
我提交的页面没有上传文件:
请帮助我。
由于
答案 0 :(得分:0)
将文件上传代码块放在if(isset($_FILES['file_name'])){}
中,即检查文件是否已过帐。因为正如您所说的那样,当您没有选择任何文件时发生错误,因此最好在运行上传代码之前检查文件是否已发布。
希望这有助于解决您的问题。
答案 1 :(得分:0)
正如您所说,当您没有选择任何文件时,它会向您显示错误,那么您需要更新if
条件
$filename = $_FILES['file_name']['name'];
if(!empty($filename))
到
$filename = $_FILES['file_name']['error'];
if($filename != 4) // Check no file is uploaded
php文档中有一节关于file handling。您会发现可以从file-upload-errors
检查各种错误UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
<...>
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.