我正在创建一个表单,用户最多可以上传4张图片并更改上传的图片。照片会上传到文件夹上传/ 。
如果文件夹中已存在任何图片,表单将显示现有图片,以便用户可以检查是否更改图片。
HTML& PHP代码如下:
<form name="upload_form" action="upload.php">
<div id="upload_block0" class="upload_block" style="margin: 1rem;">
<?php
if( file_exists("upload/pic0.jpg")){
echo "<img src='upload/pic0.jpg'>";
}
?>
<input type="file" name="picture[]" id="picture" />
<button onclick="removeBlock()">Remove</button>
</div>
<div id="upload_block1" class="upload_block" style="margin: 1rem;">
<?php
if( file_exists("upload/pic1.jpg")){
echo "<img src='upload/pic1.jpg'>";
}
?>
<input type="file" name="picture[]" id="picture" />
<button onclick="removeBlock()">Remove</button>
</div>
<div id="upload_block2" class="upload_block" style="margin: 1rem;">
<?php
if( file_exists("upload/pic2.jpg")){
echo "<img src='upload/pic2.jpg'>";
}
?>
<input type="file" name="picture[]" id="picture" />
<button onclick="removeBlock()">Remove</button>
</div>
<div id="upload_block3" class="upload_block" style="margin: 1rem;">
<?php
if( file_exists("upload/pic3.jpg")){
echo "<img src='upload/pic3.jpg'>";
}
?>
<input type="file" name="picture[]" id="picture" />
<button onclick="removeBlock()">Remove</button>
</div>
<input type="submit" />
<button onclick="addBlock()">Upload More</button>
</form>
<?php //upload.php
for ($i = 0; $i < count($_FILES["picture"]["name"]); $i++) {
move_uploaded_file($_FILES["picture"]["tmp_name"][$i], "upload/pic".$i
}
?>
如果用户不想要旧图片,可以点击<input type="file">
上传新图片;
如果他们仍然想要旧的,我怎样才能让<input type="file">
获取现有图片的tmp_name,以便 upload.php 可以上传图片?
非常感谢!
答案 0 :(得分:0)
在没有上传文件时忽略move_uploaded_file()
for ($i = 0; $i < count($_FILES["picture"]["name"]); $i++) {
if ($_FILES["picture"]['size'] > 0 && $_FILES['picture']['error'] == 0) {
// upload file when there are uploaded file
move_uploaded_file($_FILES['picture']['tmp_name'][$i], 'upload/pic' . $i);
}
}