3

我让这个厨房在我想要的地方工作了大约 65%。我想知道是否有人可以查看以下代码并告诉我如何将多张图片上传到我的画廊。

这是代码。

简单的管理表单代码:

    <form enctype="multipart/form-data" action="uploader.php" method="POST">


        Category: <select class="text" name="dataType[]">
        <option value="treeremoval" selected="selected">treeremoval</option>
        <option value="treetrimming" >treetrimming</option>
        <option value="treebracing" >treebracing</option>
        <option value="stumpgrinding" >stumpgrinding</option>
        <option value="firewood" >firewood</option>
        <option value="cleanup" >cleanup</option>
        </select>
<br /><br />

    Caption: <input type="text" name="title[]">
<br /><br />

Image to upload: <input type="file" name="image[]" />
<br /><br />






        Category: <select class="text" name="dataType[]">
        <option value="treeremoval" selected="selected">treeremoval</option>
        <option value="treetrimming" >treetrimming</option>
        <option value="treebracing" >treebracing</option>
        <option value="stumpgrinding" >stumpgrinding</option>
        <option value="firewood" >firewood</option>
        <option value="cleanup" >cleanup</option>
        </select>
<br /><br />

    Caption: <input type="text" name="title[]">
<br /><br />

Image to upload: <input type="file" name="image[]" />
<br /><br />



    <input type="submit" value="Upload">
</form>

uploader.php 代码:


    <?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");

$dataType = mysql_real_escape_string($_POST["dataType"][$i]);
$title = mysql_real_escape_string($_POST["title"][$i]);

$fileData = pathinfo(basename($_FILES["image"]["name"][$i]));

$fileName = uniqid() . '.' . $fileData['extension'][$i];

$target_path = ($_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName);


for($i=0;$i<count($_FILES["image"]["name"]);$i++){

 $dataType = mysql_real_escape_string($_POST["dataType"][$i]);  // get the dataType with the same key - $i
    $title = mysql_real_escape_string($_POST["title"][$i]);   // get the title with the same key - $i

    $fileData = pathinfo(basename($_FILES["image"]["name"][$i]));
while(file_exists($target_path))
{
    $fileName = uniqid() . '.' . $fileData['extension'];
    $target_path = ($_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName);
}

 if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path))
    {    // The file is in the images/gallery folder. Insert record into database by
    // executing the following query:
     $sql="INSERT INTO images (data_type, title, file_name)"."VALUES('$dataType','$title','$fileName')";
     $retval = mysql_query($sql);



echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />
     <a href='index.php'>Add another image</a><br />";


}
else
{
 echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
    }
} // close your foreach
?>

我尝试将表单代码复制 4 次,但它只会将 1 张图片上传到图库。

任何帮助将不胜感激。

谢谢你!

4

4 回答 4

5

在您的表单中,添加多个文件输入。一种方法是使用数组名称 -image[]

Image to upload: <input type="file" name="image[]" /><br />
Image to upload: <input type="file" name="image[]" /><br />
Image to upload: <input type="file" name="image[]" /><br />
....  // as many as you want. Just be aware of upload_max_filesize, memory_limit, post_max_size etc.
<br /> 

然后在你的uploader.php, 用 for 循环包装你的文件上传代码

for($i=0;$i<count($_FILES["image"]["name"]);$i++){

    $fileData = pathinfo(basename($_FILES["image"]["name"][$i]));

     ...

    if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path))
    {
      ...

      echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />";

    }
    else
    {
     echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
    }
} // close your foreach

该手册有很大一部分介绍了上传文件时的常见陷阱,尤其是多个文件。http://www.php.net/manual/en/features.file-upload.common-pitfalls.php


如果您想做多个其他操作,可以以相同的方式完成(我缩写了选择以减少复制/粘贴) -

<form enctype="multipart/form-data" action="uploader.php" method="POST">

    // 1st set
    Category: <select class="text" name="dataType[]" />
    ...
    </select><br />
    <br />        

    Caption: <input type="text" name="title[]" /><br />
    <br />

    Image to upload: <input type="file" name="image[]" /><br />
    <br /> 

    // 2nd set
    Category: <select class="text" name="dataType[]" />
    ...
    </select><br />
    <br />        

    Caption: <input type="text" name="title[]" /><br />
    <br />

    Image to upload: <input type="file" name="image[]" /><br />
    <br />  

   // and so on, as many as you want  
   ...
    <input type="submit" value="Upload">
</form>

和你的 php,将 for 循环放在所有元素周围

for($i=0;$i<count($_FILES["image"]["name"]);$i++){

    $dataType = mysql_real_escape_string($_POST["dataType"][$i]);  // get the dataType with the same key - $i
    $title = mysql_real_escape_string($_POST["title"][$i]);   // get the title with the same key - $i

    $fileData = pathinfo(basename($_FILES["image"]["name"][$i]));

     ...

    if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path))
    {
      ...

      echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />";

    }
    else
    {
     echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
    }
} // close your foreach

编辑
你快到了。删除 for 循环上方的重复代码。删除basename(),因为这会导致您extension失败,pathinfo()并将返回['basename'].

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");

for($i=0;$i<count($_FILES["image"]["name"]);$i++){
  if($_FILES["image"]["name"][$i] != ''){ // don't insert if file name empty
    $dataType = mysql_real_escape_string($_POST["dataType"][$i]);
    $title = mysql_real_escape_string($_POST["title"][$i]);

    $fileData = pathinfo($_FILES["image"]["name"][$i]);

    $fileName = uniqid() . '.' . $fileData['extension'];
    $target_path = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName;

    while(file_exists($target_path)){
       $fileName = uniqid() . '.' . $fileData['extension'];
       $target_path = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName;
    }     

  if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path)){    // The file is in the images/gallery folder. 
    // Insert record into database by executing the following query:
     $sql="INSERT INTO images (data_type, title, file_name) "."VALUES('$dataType','$title','$fileName')";
     $retval = mysql_query($sql);

    echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />
     <a href='index.php'>Add another image</a><br />";
  }
  else
  {
   echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
    }
  }
} // close your foreach
?>
于 2013-07-11T21:47:18.930 回答
2

显然,在版本 10(!) 之前的 Internet Explorer 中遗憾地不支持的 HTML5 功能允许您执行此操作:

<input name="upload[]" type="file" multiple="multiple" />

这也是有效的:

<input name="upload[]" type="file" multiple />

(结束斜线是兼性的,但我喜欢自闭合标签有斜线,所以我决定放斜线。)

然而,有 JavaScript 等工具显然拓宽了兼容性。就像这个 Jquery 的东西。blueimp.github.io/jQuery-File-Upload

(来源:如何使用 <input type="file"> 选择多个文件?

(我确信有一种更简单、兼容 IE 的方法,但也许是我想象出来的。不管怎样,我显然在放假前把我老师的上传文件留在了学校,所以我不能确定。)

是的。你有这个multiple="multiple"输入来完成这项工作。但它绝对不能满足您的需求。因为,你知道,没有多少人拥有 IE 10,放弃 IE 是有限制的。从那里开始,您有几个选择。

  1. 使用诸如 Modernizr 之类的工具检查与多文件输入的兼容性,如果浏览器不兼容,那么您将显示多个单文件输入而不是它。或者可能只是一个,然后,当使用前一个时,您将通过 Javascript 添加另一个。

  2. 查看该 jQuery 插件或其他类似工具以“强制”浏览器与您的多文件输入兼容。

多文件输入的用法示例:

HTML:

<form method="post" action="upload.php" enctype="multipart/form-data">
    <input name="uploads[]" type="file" multiple="multiple" />
    <input type="submit" value="Send" />
</form>

然后在 PHP 中,您的所有文件都将存储在您通常可以找到单个文件的位置,但现在它将是一个数组,您将通过添加额外的方括号层来访问它。例如,$_FILES['uploads']['name'][0]是您的第一个文件。

以下代码将允许您遍历每个文件。当然,这段代码只显示每个文件名,但是你可以改变循环的内容。

foreach ($_FILES['uploads']['name'] as $filename) {
    echo '<li>' . $filename . '</li>';
}

在这个循环中,您将像通常处理单个文件一样处理上传每个文件。

(来源:http ://css-tricks.com/snippets/html/multiple-file-input/ )

于 2013-07-11T22:13:57.683 回答
1

最简单的方法是添加多个file具有相同名称的输入(以一种形式),并添加方括号:

<input type="file" name="image[]">

然后,您可以通过添加增量编号来访问文件:

$_FILES["image"]["name"][0] 

因此,您将整个上传后的过程放入一个循环遍历文件的循环中。请注意,如果您并不总是在每个文件输入中提交图像,一些变量 (=inputs) 将保持为空,您需要将错误处理更改为不显示错误。我会这样做:

if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path)) {
     //processing...
} else if (!empty($_FILES["image"]["name"][$i]) {
     //error
}
于 2013-07-11T22:01:20.403 回答
0

我不知道我是否可以发布链接,但我发现这个正在寻找一个可以上传多个文件的系统,并希望与所有其他正在寻找这个的人分享。

MySQL

CREATE TABLE `upload_data` (
  `ID` int(5) NOT NULL AUTO_INCREMENT,
  `USER_CODE` int(4) unsigned zerofill NOT NULL,
  `FILE_NAME` varchar(200) NOT NULL,
  `FILE_SIZE` varchar(200) NOT NULL,
  `FILE_TYPE` varchar(200) NOT NULL,
  PRIMARY KEY (`ID`)
)

PHP

<?php
if(isset($_FILES['files'])){
    $errors= array();
    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];  
        if($file_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }       
        $query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
        $desired_dir="user_data";
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"user_data/".$file_name);
            }else{                                  //rename the file if another one exist
                $new_dir="user_data/".$file_name.time();
                 rename($file_tmp,$new_dir) ;               
            }
            mysql_query($query);            
        }else{
                print_r($errors);
        }
    }
    if(empty($error)){
        echo "Success";
    }
}
?>


<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="files[]" multiple/>
    <input type="submit"/>
</form>

而已!希望对某人有所帮助^^完整的解释和所有学分: http ://techstream.org/Web-Development/PHP/Multiple-File-Upload-with-PHP-and-MySQL

于 2014-10-28T22:32:44.203 回答