php中的多个文件上传

Posted

技术标签:

【中文标题】php中的多个文件上传【英文标题】:Multiple file upload in php 【发布时间】:2011-02-11 20:33:29 【问题描述】:

我想上传多个文件并将它们存储在一个文件夹中,并获取路径并将其存储在数据库中...任何您寻找的执行多个文件上传的好例子...

注意:文件可以是任何类型...

【问题讨论】:

See uploading multiple files. 这里有一个很好的例子供你学习:EXAMPLE @sarfraz 我有一个周末......刚才我尝试了这个例子,它太简单了 @sarfraz 我试图生成 从添加点击我得到了 's on add click 但结果没有实现你能看到我发布的新问题吗 【参考方案1】:

我知道这是一篇旧帖子,但一些进一步的解释可能对尝试上传多个文件的人有用...这是您需要做的:

输入名称必须定义为数组,即 name="inputName[]" 输入元素必须有multiple="multiple"或只有multiple 在您的 php 文件中使用语法 "$_FILES['inputName']['param'][index]" 确保查找空文件名和路径,该数组可能包含空字符串。在计数之前使用array_filter()

这是一个肮脏的例子(仅显示相关代码)

html

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

PHP:

//$files = array_filter($_FILES['upload']['name']); //something like that to be used before processing files.

// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);

// Loop through each file
for( $i=0 ; $i < $total ; $i++ ) 

  //Get the temp file path
  $tmpFilePath = $_FILES['upload']['tmp_name'][$i];

  //Make sure we have a file path
  if ($tmpFilePath != "")
    //Setup our new file path
    $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];

    //Upload the file into the temp dir
    if(move_uploaded_file($tmpFilePath, $newFilePath)) 

      //Handle other code here

    
  

希望对您有所帮助!

【讨论】:

@Sven 是的,它在 HTML5 中受支持,看看这个link,我的坏主意好像 IE 不支持这个,但是……天哪,如果每个人都过去的话,我们的生活会容易得多标准...大声笑 @AndyBraham 出色的回答,为我节省了大量时间 :) @AndyBraham input 元素的multiple 属性是布尔值,这意味着您不提供值:&lt;input name="upload[]" type="file" multiple /&gt; 请参阅 HTML5 规范:w3.org/TR/2011/WD-html5-20110525/… 值得一提的是,用户必须一次选择所有文件。任何进一步的选择尝试都将取消之前的选择。 @AlienBishop 在这里不太正确,multiple="multiple" 非常好,并且作为替代方案包含在规范中。【参考方案2】:

可以选择多个文件,然后使用&lt;input type='file' name='file[]' multiple&gt;上传 上传的示例 php 脚本:

<html>
<title>Upload</title>
<?php
    session_start();
    $target=$_POST['directory'];
        if($target[strlen($target)-1]!='/')
                $target=$target.'/';
            $count=0;
            foreach ($_FILES['file']['name'] as $filename) 
            
                $temp=$target;
                $tmp=$_FILES['file']['tmp_name'][$count];
                $count=$count + 1;
                $temp=$temp.basename($filename);
                move_uploaded_file($tmp,$temp);
                $temp='';
                $tmp='';
            
    header("location:../../views/upload.php");
?>
</html>

所选文件作为数组接收

$_FILES['file']['name'][0] 存储第一个文件的名称。$_FILES['file']['name'][1] 存储第二个文件的名称。 等等。

【讨论】:

上传多个文件的时候有没有办法用JS访问每个文件的文件路径? for instance, for single files you can simply query fileInput.value, but i've noticed that when multiple files are selected fileInput.value still only outputs one path...【参考方案3】:

这个简单的脚本对我有用。

<?php

foreach($_FILES as $file)
  //echo $file['name']; 
  echo $file['tmp_name'].'</br>'; 
  move_uploaded_file($file['tmp_name'], "./uploads/".$file["name"]);


?>

【讨论】:

【参考方案4】:

HTML

    id='dvFile'创建div;

    创建一个button

    onclick那个按钮调用函数add_more()

JavaScript

function  add_more() 
  var txt = "<br><input type=\"file\" name=\"item_file[]\">";
  document.getElementById("dvFile").innerHTML += txt;

PHP

if(count($_FILES["item_file"]['name'])>0)
  
//check if any file uploaded
 $GLOBALS['msg'] = ""; //initiate the global message
  for($j=0; $j < count($_FILES["item_file"]['name']); $j++)
  //loop the uploaded file array
   $filen = $_FILES["item_file"]['name']["$j"]; //file name
   $path = 'uploads/'.$filen; //generate the destination path
   if(move_uploaded_file($_FILES["item_file"]['tmp_name']["$j"],$path)) 

   //upload the file
    $GLOBALS['msg'] .= "File# ".($j+1)." ($filen) uploaded successfully<br>";
    //Success message
   
  
 
 else 
  $GLOBALS['msg'] = "No files found to upload"; //No file upload message 

通过这种方式,您可以根据需要添加文件/图像,并通过 php 脚本处理它们。

【讨论】:

替换这个 document.getElementById("dvFile").innerHTML += txt; with $( "#dvFile" ).append(txt ); 它将保存您的附件 这个答案已经过时(在我看来,对于如此简单的事情来说太复杂了)。要获得正确答案,请查看@rjv's @VladimirNul 有没有办法在上传多个文件时用JS访问每个文件的文件路径? for instance, for single files you can simply query fileInput.value, but i've noticed that when multiple files are selected fileInput.value still only outputs one path... @Anthony 听起来你是在用 javascript 做的,我不明白这一点。请检查 rjv 的答案。【参考方案5】:

这与上传一个文件没有什么不同 - $_FILES 是一个包含所有上传文件的数组。

PHP手册中有一个章节:Uploading multiple files

如果您想在用户端轻松选择多个文件上传(一次选择多个文件而不是填写上传字段),请查看SWFUpload。它的工作方式与普通文件上传表单不同,但需要 Flash 才能工作。 SWFUpload 与 Flash 一起被淘汰。检查其他较新的答案以了解现在正确的方法。

【讨论】:

这个答案已经过时了。要获得正确答案,请查看@rjv's 是的。编辑以反映这一点。【参考方案6】:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<?php
$max_no_img=4; // Maximum number of images value to be set here

echo "<form method=post action='' enctype='multipart/form-data'>";
echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>";
for($i=1; $i<=$max_no_img; $i++)
echo "<tr><td>Images $i</td><td>
<input type=file name='images[]' class='bginput'></td></tr>";


echo "<tr><td colspan=2 align=center><input type=submit value='Add Image'></td></tr>";
echo "</form> </table>";
while(list($key,$value) = each($_FILES['images']['name']))

    //echo $key;
    //echo "<br>";
    //echo $value;
    //echo "<br>";
if(!empty($value))   // this will check if any blank field is entered
$filename =rand(1,100000).$value;    // filename stores the value

$filename=str_replace(" ","_",$filename);// Add _ inplace of blank space in file name, you can remove this line

$add = "upload/$filename";   // upload directory path is set
//echo $_FILES['images']['type'][$key];     // uncomment this line if you want to display the file type
//echo "<br>";                             // Display a line break
copy($_FILES['images']['tmp_name'][$key], $add); 
echo $add;
    //  upload the file to the server
chmod("$add",0777);                 // set permission to the file.


?>
</body>
</html>

【讨论】:

这个答案已经过时了。要获得正确答案,请查看@rjv's【参考方案7】:

很简单,先计算文件数组,然后在while循环中你可以轻松地做到这一点

$count = count($_FILES'item_file']['name']);

现在你得到了正确的文件总数。

在while循环中这样做:

$i = 0;
while($i<$count)

    Upload one by one like we do normally
    $i++;

【讨论】:

这里少了点东西,请看@rjv的回答。【参考方案8】:

这是我编写的一个函数,它返回一个更易于理解的 $_FILES 数组。

function getMultiple_FILES() 
    $_FILE = array();
    foreach($_FILES as $name => $file) 
        foreach($file as $property => $keys) 
            foreach($keys as $key => $value) 
                $_FILE[$name][$key][$property] = $value;
            
        
    
    return $_FILE;

【讨论】:

【参考方案9】:

我用错误元素运行 foreach 循环,看起来像

 foreach($_FILES['userfile']['error'] as $k=>$v)
 
    $uploadfile = 'uploads/'. basename($_FILES['userfile']['name'][$k]);
    if (move_uploaded_file($_FILES['userfile']['tmp_name'][$k], $uploadfile)) 
    
        echo "File : ", $_FILES['userfile']['name'][$k] ," is valid, and was                      successfully uploaded.\n";
    

    else 
    
        echo "Possible file : ", $_FILES['userfile']['name'][$k], " upload attack!\n";
       

 

【讨论】:

【参考方案10】:

刚刚遇到以下解决方案:

http://www.mydailyhacks.org/2014/11/05/php-multifile-uploader-for-php-5-4-5-5/

它是一个现成的 PHP 多文件上传脚本,带有一个表单,您可以在其中添加多个输入和一个 AJAX 进度条。它应该在服务器上解压后直接工作......

【讨论】:

【参考方案11】:

我们可以通过使用下面的脚本轻松地使用 php 上传多个文件。

Download Full Source code and preview

<?php
if (isset($_POST['submit'])) 
    $j = 0; //Variable for indexing uploaded image 

 $target_path = "uploads/"; //Declaring Path for uploaded images
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) //loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 
        $file_extension = end($ext); //store extensions in the variable

  $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array       

   if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
                && in_array($file_extension, $validextensions)) 
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) //if file moved to uploads folder
                echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
             else //if file was not moved.
                echo $j. ').<span id="error">please try again!.</span><br/><br/>';
            
         else //if file size and file type was incorrect.
            echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
        
    

?>

【讨论】:

【参考方案12】:
$property_images = $_FILES['property_images']['name'];
    if(!empty($property_images))
    
        for($up=0;$up<count($property_images);$up++)
        
            move_uploaded_file($_FILES['property_images']['tmp_name'][$up],'../images/property_images/'.$_FILES['property_images']['name'][$up]);
        
    

【讨论】:

请查看此URL,它将有助于提升您的内容质量【参考方案13】:

这对我有用。我必须上传文件,存储文件名,并且我还需要从输入字段中存储额外的 inof,并且每个文件名都有一个记录。 我使用了 serialize() 然后将其添加到主 sql 查询中。

  class addReminder extends dbconn 
    public function addNewReminder()

           $this->exdate = $_POST['exdate'];
           $this->name = $_POST['name'];
           $this->category = $_POST['category'];
           $this->location = $_POST['location'];
           $this->notes = $_POST['notes'];



           try 

                     if(isset($_POST['submit']))
                       $total = count($_FILES['fileUpload']['tmp_name']);
                       for($i=0;$i<$total;$i++)
                         $fileName = $_FILES['fileUpload']['name'][$i];
                         $ext = pathinfo($fileName, PATHINFO_EXTENSION);
                         $newFileName = md5(uniqid());
                         $fileDest = 'filesUploaded/'.$newFileName.'.'.$ext;
                         $justFileName = $newFileName.'.'.$ext;
                         if($ext === 'pdf' || 'jpeg' || 'JPG')
                             move_uploaded_file($_FILES['fileUpload']['tmp_name'][$i], $fileDest);
                             $this->fileName = array($justFileName);
                             $this->encodedFileNames = serialize($this->fileName);
                             var_dump($this->encodedFileNames);
                         else
                           echo $fileName . ' Could not be uploaded. Pdfs and jpegs only please';
                         
                       

                    $sql = "INSERT INTO reminders (exdate, name, category, location, fileUpload, notes) VALUES (:exdate,:name,:category,:location,:fileName,:notes)";
                    $stmt = $this->connect()->prepare($sql);
                    $stmt->bindParam(':exdate', $this->exdate);
                    $stmt->bindParam(':name', $this->name);
                    $stmt->bindParam(':category', $this->category);
                    $stmt->bindParam(':location', $this->location);
                    $stmt->bindParam(':fileName', $this->encodedFileNames);
                    $stmt->bindParam(':notes', $this->notes);
                    $stmt->execute();
                  

           catch(PDOException $e)
             echo $e->getMessage();
           
      
    

【讨论】:

【参考方案14】:
extract($_POST);
    $error=array();
    $extension=array("jpeg","jpg","png","gif");
    foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
            
                $file_name=$_FILES["files"]["name"][$key];
                $file_tmp=$_FILES["files"]["tmp_name"][$key];
                $ext=pathinfo($file_name,PATHINFO_EXTENSION);
                if(in_array($ext,$extension))
                
                    if(!file_exists("photo_gallery/".$txtGalleryName."/".$file_name))
                    
                        move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$file_name);
                    
                    else
                    
                        $filename=basename($file_name,$ext);
                        $newFileName=$filename.time().".".$ext;
                        move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$newFileName);
                    
                
                else
                
                    array_push($error,"$file_name, ");
                
            

您必须检查您的 HTML 代码

<form action="create_photo_gallery.php" method="post" enctype="multipart/form-data">
    <table >
        <tr>
            <td>Select Photo (one or multiple):</td>
            <td><input type="file" name="files[]" multiple/></td>
        </tr>
        <tr>
            <td colspan="2" align="center">Note: Supported image format: .jpeg, .jpg, .png, .gif</td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="Create Gallery" id="selectedButton"/></td>
        </tr>
    </table>
</form>

不错的链接:

PHP Single File Uploading with vary basic explanation.

PHP file uploading with the Validation

PHP Multiple Files Upload With Validation Click here to download source code

PHP/jQuery Multiple Files Upload With The ProgressBar And Validation (Click here to download source code)

How To Upload Files In PHP And Store In MySql Database (Click here to download source code)

【讨论】:

以上是关于php中的多个文件上传的主要内容,如果未能解决你的问题,请参考以下文章

无法从 php 中的 $_FILES 获取多个上传的文件

使用 PHP 上传多个文件 [重复]

laravel 5.7 中的多个文件上传问题

使用PHP脚本如何上传多个文件

从android应用程序上传多个图像文件到php服务器

如何使用 PHP、jQuery 和 AJAX 上传多个文件