我在Linux上使用apache,我复制并粘贴了来自https://www.w3schools.com/php/php_file_upload.asp的代码,它得到了“抱歉,上传文件时出错”,可以在最后的else语句中找到。
这是代码:
<?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.";
}
}
?>
uploadform.php:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
我甚至尝试将$target_dir = "uploads/"
更改为$target_dir = "/var/www/html/uploads/"
因为我在那里创建了uploads目录。如何获取我尝试上传的jpg文件并保存到本地服务器上的uploads文件夹中。
答案 0 :(得分:1)
这是你的代码:
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."; }
由于你得到if / else的后半部分,你知道move_uploaded_file
返回了一个错误值。
所以look at the documentation for that function:
成功时返回TRUE。
如果filename不是有效的上传文件,则不会执行任何操作,并且 move_uploaded_file()将返回FALSE。
如果filename是有效的上传文件,但某些文件无法移动 原因,不会发生任何操作,move_uploaded_file()将返回 假。此外,还会发出警告。
由于您已对该文件进行了大量检查,因此您知道它是一个有效的上传文件,因此第三段必须是解释该问题的段落。
它表示会发出警告,所以turn on all errors and warnings然后查看输出的消息。
这会告诉你问题是什么(我猜是Web服务器没有目标目录的写权限。)
答案 1 :(得分:1)
您的输出表明该文件已上传到您的临时目录 - 但该文件无法移动到您设置的目的地。
检查要将文件移动到的路径(例如$ target_file),并确保Web用户(apache,www或其他)有权写入该目录。