php php中的多个文件上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2704314/
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 07:25:21  来源:igfitidea点击:

Multiple file upload in php

phpfile-upload

提问by udaya

I want to upload multiple files and store them in a folder and get the path and store it in the database... Any good example you looked for doing multiple file upload...

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

Note:Files can be of any type...

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

回答by Andy Braham

I know this is an old post but some further explanation might be useful for someone trying to upload multiple files... Here is what you need to do:

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

  • Input name must be be defined as an array i.e. name="inputName[]"
  • Input element must have multiple="multiple"or just multiple
  • In your PHP file use the syntax "$_FILES['inputName']['param'][index]"
  • Make sure to look for empty file names and paths, the array might contain empty strings. Use array_filter()before count.
  • 输入名称必须定义为数组,即 name="inputName[]"
  • 输入元素必须有multiple="multiple"或只是multiple
  • 在您的 PHP 文件中使用语法 "$_FILES['inputName']['param'][index]"
  • 确保查找空文件名和路径,数组可能包含空字符串array_filter()计数前使用。

Here is a down and dirty example (showing just relevant code)

这是一个糟糕的示例(仅显示相关代码)

HTML:

HTML:

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

PHP:

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

    }
  }
}

Hope this helps out!

希望这会有所帮助!

回答by rjv

Multiple files can be selected and then uploaded using the
<input type='file' name='file[]' multiple>
The sample php script that does the uploading:

可以选择多个文件,然后使用执行上传
<input type='file' name='file[]' multiple>
的示例 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>

The selected files are received as an array with

所选文件作为数组接收

$_FILES['file']['name'][0]storing the name of first file.
$_FILES['file']['name'][1]storing the name of second file.
and so on.

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

回答by kdniazi

HTML

HTML

  1. create div with id='dvFile';

  2. create a button;

  3. onclickof that button calling function add_more()

  1. 创建 div id='dvFile';

  2. 创建一个button;

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

JavaScript

JavaScript

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

PHP

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 
}

In this way you can add file/images, as many as required, and handle them through php script.

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

回答by Pekka

It's not that different from uploading one file - $_FILESis an array containing any and all uploaded files.

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

There's a chapter in the PHP manual: Uploading multiple files

PHP手册中有一个章节:上传多个文件

If you want to enable multiple file uploads with easy selection on the user's end (selecting multiple files at once instead of filling in upload fields) take a look at SWFUpload. It works differently from a normal file upload form and requires Flash to work, though.SWFUpload was obsoleted along with Flash. Check the other, newer answers for the now-correct approach.

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

回答by muaz khalid

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

回答by Nick

Simple is that, just count the files array first, then in while loop you can easily do this like

简单的是,只需先计算 files 数组,然后在 while 循环中,您就可以轻松地做到这一点

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

now you got total number of files right.

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

In while loop do like this:

在while循环中这样做:

$i = 0;
while($i<$count)
{
    Upload one by one like we do normally
    $i++;
}

回答by Cheejyg

Here is a function I wrote which returns a more understandable $_FILESarray.

这是我写的一个函数,它返回一个更容易理解的$_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;
}

回答by Rohit Mandiwal

this simple script worked for me.

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

<?php

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

?>

回答by HCV

I run foreach loop with error element, look like

我用错误元素运行 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";
    }   

 }

回答by Peter

Just came across the following solution:

刚刚遇到以下解决方案:

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

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

it is a ready PHP Multi File Upload Script with an form where you can add multiple inputs and an AJAX progress bar. It should work directly after unpacking on the server...

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