【发布时间】:2019-12-20 21:13:53
【问题描述】:
我可以将图像文件的名称上传到我的数据库,但它不会保存到我的文件中
我之前曾在其他系统上尝试过此代码,并且效果很好。我不确定为什么它在我当前的系统上不起作用。
在这个系统中,我还需要以相同的形式提交图像以及其他输入(其他输入,如姓名、地址、日期等)。
我的表单代码:
<form method = "post" action="insert.php">
<label for="name">Full Name</label>
<input type="hidden" name="name" value="<?php echo $_SESSION['name']; ?>">
<label for="address">Address</label>
<textarea id="address" name="address" placeholder="" style="height:100px" class = "form control"></textarea>
//other input field
<label for="picture">Picture</label>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" name="picture" value="<?php echo $print[0]+1;?>">
<label for="date">Date & Time</label>
<input type="datetime" name="date" value="<?php date_default_timezone_set("countryname"); echo date("Y-m-d h:i:s");?>">
<input type="submit" value="Submit" name="submit">
</form>
</form>
我的上传.php:
$target_file = basename($_FILES["fileToUpload"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$directory = "upload/";
$uploadOk = 1;
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg") {
echo "Sorry, only JPG 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"], $directory)) {
echo "<script>alert('Your file has successfully been uploaded.'); window.location='insert.php';</script>";
}
else {
echo "<script>alert('Sorry, there was an error uploading your file.'); window.location='insert.php';</script>";
注意:<?php echo $print[0]+1;?> 是显示 db 中自增的最后一个值
你能指出我做错了什么以及解决方案吗?因为我已经做了很多试验和错误,但仍然找不到答案。非常感谢您的宝贵时间。
【问题讨论】:
-
“我的表单代码:” - 您不能将表单相互嵌套,这是无效的 HTML。首先去解决这个问题。
-
您应该在表单元素中提及
enctype="multipart/form-data"。 -
@Gulshan 有提到,但是在一个
form里面一个form -
@kerbholz 为什么在
form中使用form?您可以管理保存数据和上传图像,有条件地使用相同的功能。 -
@Gulshan 我不要在
form中使用form,我不是OP。