使用下面的PHP,我尝试上传多个图像。上传图片的数量可以改变。
我似乎遇到的问题是,1号图像没有被上传,但是它的文件路径被打印到了屏幕上。
代码:-
if ($_FILES['pac_img_1']['name']>""){
echo("You have uploaded the following images:-<ul>");
for ($i=1; $i<=$imagesCount; $i++){
$target_path = "files/" . $companyName . "/images/";
$target_path = $target_path . basename( $_FILES['pac_img_' . $i]['name']);
if(move_uploaded_file($_FILES['pac_img_' . $i]['tmp_name'], $target_path)) {
echo "<li><a href='". $target_path . "'>". basename( $_FILES['pac_img_' . $i]['name']). "</a></li>";
} else{
echo "There was an error uploading an image";
}
};
echo("</ul>");
}else{
echo("None uploaded");
};我将它改编自一些我以前使用过的代码,所以我怀疑我在这里犯了一个“学生式”的错误。
如果能帮上忙,我们将不胜感激。
编辑以添加通过$_POST请求从表单元素获取其值的$imagesCount。当只上传了一个图像时,该值= 0。
发布于 2012-02-16 00:31:41
您的for循环需要修改。数组索引从0开始。最后一个元素应该是Array length - 1;您的for循环需要修改为下面的代码示例。
实际上,它遍历了几个$_POST iten。他的HTML可能有这样的内容:
<input type="file" name="pac_img_1">
<input type="file" name="pac_img_2">
<input type="file" name="pac_img_3">他正试图获得这些图像。
我会以不同的方式做这件事。
HTML:
<input type="file" name="pac_img[]" />
<input type="file" name="pac_img[]" />
<input type="file" name="pac_img[]" />(请注意,您可以动态添加文件输入,而无需担心名称)
PHP:
if (count($_FILES['pac_img']) > 0){
echo("You have uploaded the following images:-<ul>");
foreach($_FILES['pac_img'] as $key => $file){
$target_path = "files/" . $companyName . "/images/";
$target_path = $target_path . basename( $file['name']);
if(move_uploaded_file($file['tmp_name'], $target_path)) {
echo "<li><a href='". $target_path . "'>". basename( $file['name'] ). "</a></li>";
} else{
echo "There was an error uploading an image";
}
}
echo("</ul>");
}else{
echo("None uploaded");
}最后,但并非最不重要的一点是:始终检查上传的文件是否如它们所宣称的那样。(http://www.acunetix.com/websitesecurity/upload-forms-threat.htm)
发布于 2012-02-16 00:09:51
即使我根本不是一个笨蛋,我也会试着改变
for ($i=1; $i<=$imagesCount; $i++){至
for ($i=0; $i<=$imagesCount; $i++){也许是-or
for ($i=0; $i < $imagesCount; $i++){这取决于$imagesCount的设置方式。
发布于 2012-02-16 00:16:48
您的for循环需要修改。数组索引从0开始。最后一个元素应为数组长度- 1;
您的for循环需要修改为以下代码示例。
if ($_FILES['pac_img_1']['name']>""){
echo("You have uploaded the following images:-<ul>");
for ($i=0; $i<$imagesCount; $i++){
$target_path = "files/" . $companyName . "/images/";
$target_path = $target_path . basename( $_FILES['pac_img_' . $i]['name']);
if(move_uploaded_file($_FILES['pac_img_' . $i]['tmp_name'], $target_path)) {
echo "<li><a href='". $target_path . "'>". basename( $_FILES['pac_img_' . $i]['name']). "</a></li>";
} else{
echo "There was an error uploading an image";
}
};
echo("</ul>");
}else{
echo("None uploaded");
};https://stackoverflow.com/questions/9296774
复制相似问题