将多个图像文件上传到php mysql库

时间:2013-07-11 21:17:49

标签: php mysql multifile-uploader

我得到的这个厨房大约占我希望它的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 个答案:

答案 0 :(得分: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
?>

答案 1 :(得分: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

(资料来源:How to select multiple files with <input type="file">?

(我确信有一个更简单的,IE兼容的方法,但也许我想象它。无论哪种方式,我显然在离开度假之前离开我的老师在学校上传文档,所以我可以'我知道肯定。)

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

  1. 使用Modernizr等工具检查多文件输入的兼容性,如果浏览器不兼容,则会显示多个单文件输入,而不是它。或者也许只有一个,然后,当你使用上一个时,你会通过Javascript添加另一个。

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

  3. 用法示例多文件输入:

    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/

答案 2 :(得分:1)

最简单的方法是添加多个file输入(在一个表单中),使用相同的名称,添加方括号:

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

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

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

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

if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path)) {
     //processing...
} else if (!empty($_FILES["image"]["name"][$i]) {
     //error
}

答案 3 :(得分: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