【发布时间】:2020-11-15 16:09:46
【问题描述】:
我正在使用 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>';
}
}
}
【问题讨论】:
-
我相信您需要将 enctype 添加到您的
<form>标签中。即enctype="multipart/form-data"。见w3schools.com/php/php_file_upload.asp -
在
<form>元素上设置enctype="multipart/form-data"以指定文件上传的正确编码。您可能想要检查!empty($_FILES)而不是isset($_POST['image'])。此外,您已经定义了一组列入白名单的扩展,但您没有对它做任何事情(请注意变量名中的拼写错误 -> 扩展 *)。 -
添加 enctype 后,它似乎正在上传图像,但是没有创建表输入,并且 100% 之后的文件不在它应该在的文件夹中。这一定是我看不到的愚蠢的东西..@RoAchterberg
-
这真的是我没有看到的愚蠢...否则要上传,因此如果图像是唯一的,则不会发生任何事情。