php - PHP图像上传未将图像上传到目标目录
问题描述
问题:
我创建了一个upload.php文件,其中包含一个 HTML 表单和上传图片所需的 PHP 代码,我使用 XAMPP localhost:
htdocs/web2/assets/upload.php
我想将图像上传到upload
同一目录中的文件夹:
htdocs/web2/assets/uploads/
脚本:
<?php
<form action="?" method="post" enctype="multipart/form-data">
<!--wrap input button as around pre-existing image -->
<?php
echo '<label class="profile_gallery_image_in"><input type="file" name="fileToUpload" id="fileToUpload" onchange="form.submit()"/><p class="label"></p><img class="myImg" src='.$image.' height="100%" width="100%" /></label>';
?>
</form>
<!-- Commence Photo Upload -->
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(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;
}
}
?>
表单设置为在输入类型更改时自动提交。这似乎工作正常并且表单正在提交。
但是,我没有上传任何实际图像,也没有任何错误。
我该如何解决这个问题?
解决方案
代码中似乎有错误。您可以使用以下代码上传图片。
<?php
if(isset($_FILES['image'])){
$errors= array();
$dir = "images/";
$file_name = $_FILES['image']['name'];
$file_name = $dir. $file_name;
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$tmp = explode('.',$_FILES['image']['name']);
$file_ext=strtolower(end($tmp));
$extensions= array("jpeg","jpg","png","gif");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a GIF, JPEG or PNG file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp, $file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>
<form action = "" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "image" />
<input type = "submit"/>
</form>
</body>
</html>
推荐阅读
- php - 当mysql查询死亡但查询在dbms中有效时如何修复我的代码?
- php - 在数据表插件上的 mysql WHERE 子句上使用 GET 方法不起作用
- python - 在 python 3.7 中安装 pyhook “找不到满足 pyHook 要求的版本”
- mysql - GROUP BY 一列并显示多列
- javascript - 如何在 JavaScript 中将数字转换为 CPF 格式?
- python - 在 python 中从 Excel 转换为 CSV 时排除工作表
- javascript - PHP登录算法未重定向到下一页(不确定连接到数据库)
- linux - 构建glibc时“制作共享对象时无法使用”
- java - 将字符串 ["Scenario 1", "Scenario 2"] 转换为数组
- abap - 通过 CALL METHOD cmd_ei_api=>maintain_bapi 在 XD02 添加新的电子邮件客户