[英]Image uploading doesn't work
伙计们..我想将图像上传到某个文件夹名称“ uploads”,然后在数据库中插入该图像的名称,问题是他没有上传图像。
所以我有这个基本的HTML代码:
<form action="newimage.php" method="POST"> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12"> <div class="form-group"> <input type="file" name="pic" id="pic"> </div> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form>
这是我的PHP页面
<?php $mysqli = new mysqli("localhost", "root", "", "homepage"); if (mysqli_connect_errno()) { printf("Connect failed: %s\\n", mysqli_connect_error()); exit(); } $name = "somethinghere"; #do upload $target_dir = "uploads"; $temp = explode(".", $_FILES["pic"]["name"]); $newfilename = $target_dir . '/Foto-' . $name . '.' . end($temp); if (move_uploaded_file($_FILES['pic']['tmp_name'], $newfilename) ) { $productimage = 'Foto-' . $name . '.' . end($temp); } else { $productimage = ''; } $sql = "INSERT INTO galeria_front (image_name) VALUES ('$productimage')"; if ($mysqli->query($sql) === TRUE) { header("Location: galery.php"); } else { echo "Error: " . $sql . "<br>" . $mysqli->error; } $mysqli->close(); ?>
如您所见,我有一个有效的连接,并尝试将productimage插入数据库表中,但是由于某种原因,它正在输入else {}并使我的productimage在数据库上为空,这意味着上述上载不起作用。
PS(请原谅我英语不好)
尝试添加这些
<form action="newimage.php" method="POST" enctype="multipart/form-data">
</form
将脚本更改为此
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !=
"jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been
uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
您缺少enctype =“ multipart / form-data”
<form action="/process.php" method="post" enctype="multipart/form-data"></form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.