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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17603685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:09:24  来源:igfitidea点击:

uploading multiple image files to php mysql gallery

phpmysqlmultifile-uploader

提问by cwd

I got this galley working about 65% of where I want it to be. I was wondering if someone could look at the following code and tell me how to upload multiple images to my gallery.

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

Here is the code.

这是代码。

Simple admin form code:

简单的管理表单代码:

    <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 code:

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
?>


I tried duplicating the form code 4 times, but it would only upload 1 image to the gallery.

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

Any help would be greatly appreciated.

任何帮助将不胜感激。

Thank You!

谢谢你!

回答by Sean

In your form, add multiple file inputs. One way is to use an array name - image[]

在您的表单中,添加多个文件输入。一种方法是使用数组名称 -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 /> 

Then in your uploader.php, wrap your file upload code with a for loop

然后在您的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

the manual has a great section on common pitfalls when uploading files, especially multiple. http://www.php.net/manual/en/features.file-upload.common-pitfalls.php

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



If you want to do multiple of the others, it can be done the same way (I abbreviated the selects to reduce copy/paste) -

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

<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>

and your php, put the for loop around all the elements

和你的 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


edit
you are almost there. Remove the duplicate code above the for loop. Remove basename(), as this is causing your extensionto fail, and pathinfo()will return the ['basename'].

编辑
你快到了。删除 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
?>

回答by Ariane

Apparently, an HTML5 feature that's sadly not supported in Internet Explorer before version 10(!) allows you to do this:

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

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

This is also valid:

这也是有效的:

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

(The end slash is facultative, but I like self-closing tags to have a slash, so I decided to put slashes.)

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

However there are JavaScript, etc. tools that apparently widen the compatibility. Like this Jquery thing. blueimp.github.io/jQuery-File-Upload

然而,有一些 JavaScript 等工具显然扩大了兼容性。喜欢这个 Jquery 的东西。blueimp.github.io/jQuery-File-Upload

(Source: How to select multiple files with <input type="file">?)

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

(I was sure there was a simpler, IE-compatible method, but maybe I imagined it. Either way, I apparently left the upload documentation from my teacher at school before leaving for the holidays, so I can't know for sure.)

(我确信有一种更简单的、与 IE 兼容的方法,但也许是我想象的。无论哪种方式,我显然都在假期前离开了学校老师的上传文档,所以我不确定。)

So... yeah. You have this multiple="multiple"input that does the job. But it's definitely not compatible enough for your needs. Because, you know, not many people have IE 10, and there's a limit to ditching IE. From there on, you have a few choices.

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

  1. Check for compatibility with multi-file inputs using a tool such as Modernizr, and if the browser is not compatible, then instead of it, you'll display several single-file inputs. Or maybe just one, and then, you'd add another through Javascript when the previous one is used.

  2. Look into that jQuery plugin or other similar tools to "force" browsers to be compatible with your multi-file input.

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

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

Usage example a multi-file input:

使用示例多文件输入:

HTML:

HTML:

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

Then in PHP, all your files will be stored where you usually find your single file, except that it'll be an array, now, and you'll access it by adding an additional layer of square brackets. For example, $_FILES['uploads']['name'][0]is your first file.

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

The following code will allow you to iterate over every single file. Of course, this code only displays every file name, but you can change the content of the loop.

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

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

And inside this loop, you'll process to upload each file as you normally would for a single file.

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

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

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

回答by user1666456

The easiest way is to add multiple fileinputs (in one form) with the same name, adding square brackets:

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

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

You can then access the files by adding an incremental number:

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

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

So you put the whole after-upload process into a loop iterating through the files. Please note that in case you do not always submit an image with each file input, some variables (=inputs) will stay empty and you need to change your error handling to not showing an error then. I'd do it like this:

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

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

回答by Felipe Lima

I don't know if I can post links, but i found this looking for a system that upload multiples files, and want to share with all other that are looking for this too.

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

MySQL

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

<?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>

That's it! Hope help someone ^^ Complete explanations and all credits to: http://techstream.org/Web-Development/PHP/Multiple-File-Upload-with-PHP-and-MySQL

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