我试图在数据库中上传图片,但是当我检查它是否已上传时,该字段为空。我还想限制上传文件类型格式jpeg,png和gif。请帮忙
HTML
<form enctype="multipart/form-data" action="subePic.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
PHP
<?php
require('conecta.php');
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$xSQL = "INSERT INTO FOTOS (PIC) VALUES(?)";
$stmt = $oConni->prepare($xSQL);
$stmt->bind_param('s', $data);
$stmt->execute() or die($oConni->error);
$stmt->close();
if(!$xSQL){
die("Database query failed: ". mysql_error());
}
print "Su foto fue subida con éxito";
}
else{
print "Error: no se subió ninguna imagen a la BD";
}
?>
答案 0 :(得分:2)
如果超出最大文件大小(100kb不多),$ _FILES包含错误消息2,文件大小显示为0.
您可以查看以下内容:
if($_FILES['image']['error'] !== 0) { ... error handling }
错误代码可在此处找到:http://php.net/manual/en/features.file-upload.errors.php
答案 1 :(得分:1)
用于类型检查和大小你应该有这样的东西:
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 90000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{
echo "Invalid file";
}
用于插入图像,您应该这样:
if(isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query ="INSERT INTO tbl_images(image)VALUES('".$data."')";
$results=mysql_query($query) or die(mysql_error());
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
}
你可以使用prepare而不是mysql_query它是基于你的conecta.php