我正在使用this.form.submit();来上传在选择完图片后立即上传并传递一些其他信息。
我遇到了一个问题,提交工作正常,可以通过post传递id,但是图片没有上传,名称也没有插入到数据库中,可能会添加类似于0_的名称,但这是不正确的,因为图像名称不存在于表中,所以它应该在没有任何循环的情况下通过if(file_exists)。
有什么想法吗?
<form id='image_upload' name='image_upload' action='customer_logo.php' method='post'>
<input type="hidden" name='id' id='id' value='<?php echo $cust_id; ?>'>
<input type='text' style="background-color:#93CD60; border-radius: 5px; color:white; font-size:17px; width:140px; text-align:center; cursor:pointer;" id='image_text' name='image_text' value="Add Logo"> </input>
<input type='file' name='image' id='image' style='visibility: hidden' accept="image/*" onchange="this.form.submit();" />
</form>
以下是 PHP 代码:
if (isset ($_POST['image'])) {
$cust_id = $_POST['id'];
$images = $_FILES['image']['name'];
$tmp_dir = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
if (!is_dir('img/logotipa/'.$cust_id)){
mkdir('img/logotipa/'.$cust_id, 0777, true);
}
$upload_dir = 'img/logo/'.$cust_id.'/';
$imgExt = strtolower(pathinfo($images,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$up_image = $images;
if (file_exists($upload_dir.$images)){
$counter = 0;
while (file_exists($upload_dir.$up_image)){
$up_image = $counter.'_'.$images;
$counter++;
}
move_uploaded_file($tmp_dir, $upload_dir.$images);
$stmt = $conn->prepare('INSERT INTO logos(customer_id, logo) VALUES (:ucid, :upic)');
$stmt->bindParam(':ucid', $cust_id);
$stmt->bindParam(':upic', $up_image);
if ($stmt->execute()){
echo '<script>window.location.href = "customer_logo.php";</script>';
}
}
}
<form>
标签中添加enctype
属性,即enctype="multipart/form-data"
。请参考https://www.w3schools.com/php/php_file_upload.asp。 - Reed<form>
元素上设置enctype="multipart/form-data"
以指定文件上传的正确编码。您可能想要检查!empty($_FILES)
而不是isset($_POST['image'])
。此外,您已经定义了一个白名单扩展名数组,但您没有对其进行任何操作(并注意变量名中的拼写错误 -> extensions *)。 - Ro Achterberg