如何使用 HTTP POST 选择和上传带有 HTML 和 PHP 的多个文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1175347/
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
How can I select and upload multiple files with HTML and PHP, using HTTP POST?
提问by stalepretzel
I have experience doing this with single file uploads using <input type="file">. However, I am having trouble doing uploading more than one at a time.
我有使用<input type="file">. 但是,我无法一次上传多个。
For example, I'd like to be able to select a series of images, then upload them to the server, all at once.
例如,我希望能够选择一系列图像,然后一次性将它们上传到服务器。
It would be great to use a single file input control, if possible.
如果可能,最好使用单个文件输入控件。
Does anyone know how to accomplish this? Thanks!
有谁知道如何做到这一点?谢谢!
回答by Mark E. Haase
This is possible in HTML5. Example (PHP 5.4):
这在HTML5 中是可能的。示例(PHP 5.4):
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
</body>
</html>
Here's what it looks like in Chrome after selecting 2 items in the file dialog:
这是在文件对话框中选择 2 个项目后在 Chrome 中的样子:


And here's what it looks like after clicking the "Upload" button.
这是单击“上传”按钮后的样子。


This is just a sketch of a fully working answer. See PHP Manual: Handling file uploadsfor more information on proper, secure handling of file uploads in PHP.
这只是一个完全有效的答案的草图。有关在PHP 中正确、安全地处理文件上传的更多信息,请参阅PHP 手册:处理文件上传。
回答by Epoxys
There are a few things you need to do to create a multiple file upload, its pretty basic actually. You don't need to use Java, Ajax, Flash. Just build a normal file upload form starting off with:
创建多文件上传需要做一些事情,实际上它非常基本。您不需要使用 Java、Ajax、Flash。只需构建一个普通的文件上传表单,开始:
<form enctype="multipart/form-data" action="post_upload.php" method="POST">
Then the key to success;
那么成功的关键;
<input type="file" name="file[]" multiple />
<input type="file" name="file[]" multiple />
do NOT forget those brackets! In the post_upload.php try the following:
不要忘记那些括号!在 post_upload.php 中尝试以下操作:
<?php print_r($_FILES['file']['tmp_name']); ?>
Notice you get an array with tmp_name data, which will mean you can access each file with an third pair of brackets with the file 'number' example:
请注意,您获得了一个带有 tmp_name 数据的数组,这意味着您可以使用第三对括号和文件“编号”示例访问每个文件:
$_FILES['file']['tmp_name'][0]
You can use php count() to count the number of files that was selected. Goodluck widdit!
您可以使用 php count() 来计算所选文件的数量。祝你好运!
回答by Thaps
Full solution in Firefox 5:
Firefox 5 中的完整解决方案:
<html>
<head>
</head>
<body>
<form name="uploader" id="uploader" action="multifile.php" method="POST" enctype="multipart/form-data" >
<input id="infile" name="infile[]" type="file" onBlur="submit();" multiple="true" ></input>
</form>
<?php
echo "No. files uploaded : ".count($_FILES['infile']['name'])."<br>";
$uploadDir = "images/";
for ($i = 0; $i < count($_FILES['infile']['name']); $i++) {
echo "File names : ".$_FILES['infile']['name'][$i]."<br>";
$ext = substr(strrchr($_FILES['infile']['name'][$i], "."), 1);
// generate a random new file name to avoid name conflict
$fPath = md5(rand() * time()) . ".$ext";
echo "File paths : ".$_FILES['infile']['tmp_name'][$i]."<br>";
$result = move_uploaded_file($_FILES['infile']['tmp_name'][$i], $uploadDir . $fPath);
if (strlen($ext) > 0){
echo "Uploaded ". $fPath ." succefully. <br>";
}
}
echo "Upload complete.<br>";
?>
</body>
</html>
回答by MitMaro
If you want to select multiple files from the file selector dialog that displays when you select browse then you are mostly out of luck. You will need to use a Java applet or something similar (I think there is one that use a small flash file, I will update if I find it). Currently a single file input only allows the selection of a single file.
如果您想从选择浏览时显示的文件选择器对话框中选择多个文件,那么您很不走运。您将需要使用 Java 小程序或类似的东西(我认为有一个使用小 Flash 文件,如果找到我会更新)。目前单个文件输入只允许选择单个文件。
If you are talking about using multiple file inputs then there shouldn't be much difference from using one. Post some code and I will try to help further.
如果您正在谈论使用多个文件输入,那么使用一个输入应该没有太大区别。发布一些代码,我会尝试进一步提供帮助。
Update: There is one method to use a single 'browse' button that uses flash. I have never personally used this but I have read a fair amount about it. I think its your best shot.
更新:有一种方法可以使用使用 Flash 的单个“浏览”按钮。我从来没有亲自使用过这个,但我已经阅读了大量关于它的内容。我认为这是你最好的镜头。
回答by pooya laryan
in the first you should make form like this :
首先,您应该制作这样的表格:
<form method="post" enctype="multipart/form-data" >
<input type="file" name="file[]" multiple id="file"/>
<input type="submit" name="ok" />
</form>
that is right . now add this code under your form code or on the any page you like
没错。现在将此代码添加到您的表单代码下或您喜欢的任何页面上
<?php
if(isset($_POST['ok']))
foreach ($_FILES['file']['name'] as $filename) {
echo $filename.'<br/>';
}
?>
it's easy... finish
很简单……完成
回答by Torandi
If you use multiple input fields you can set name="file[]" (or any other name). That will put them in an array when you upload them ($_FILES['file'] = array ({file_array},{file_array]..))
如果您使用多个输入字段,您可以设置 name="file[]"(或任何其他名称)。当您上传它们时,这会将它们放入一个数组中 ( $_FILES['file'] = array ({file_array},{file_array]..))
回答by antelove
<form action="" method="POST" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file[]" multiple/>
<input type="submit" name="submit" value="Upload Image" />
</form>
Using FOR Loop
使用 FOR 循环
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['file']['name']); $x++) {
$file_name = $_FILES['file']['name'][$x];
$file_tmp = $_FILES['file']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
Using FOREACH Loop
使用 FOREACH 循环
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
foreach ($_FILES['file']['name'] as $key => $value) {
$file_name = $_FILES['file']['name'][$key];
$file_tmp = $_FILES['file']['tmp_name'][$key];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
回答by Prateik Darji
i have created a php function which is used to upload multiple images, this function can upload multiple images in specific folder as well it can saves the records into the database in the following code $arrayimage is the array of images which is sent through form note that it will not allow upload to use multiple but you need to create different input field with same name as will you can set dynamic add field of file unput on button click.
我创建了一个用于上传多张图片的php函数,这个函数可以上传特定文件夹中的多张图片,也可以在下面的代码中将记录保存到数据库中 $arrayimage 是通过表单注释发送的图像数组它不允许上传使用多个,但您需要创建具有相同名称的不同输入字段,您可以设置按钮单击时取消放置的文件的动态添加字段。
$dir is the directory in which you want to save the image $fields is the name of the field which you want to store in the database
$dir 是要保存图像的目录 $fields 是要存储在数据库中的字段的名称
database field must be in array formate example if you have database imagestore and fields name like id,name,address then you need to post data like
数据库字段必须在数组格式示例中,如果您有数据库图像存储和字段名称,如 id、name、address,那么您需要发布数据,如
$fields=array("id"=$_POST['idfieldname'], "name"=$_POST['namefield'],"address"=$_POST['addressfield']);
and then pass that field into function $fields
然后将该字段传递给函数 $fields
$table is the name of the table in which you want to store the data..
$table 是您要存储数据的表的名称。
function multipleImageUpload($arrayimage,$dir,$fields,$table)
{
//extracting extension of uploaded file
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $arrayimage["name"]);
$extension = end($temp);
//validating image
if ((($arrayimage["type"] == "image/gif")
|| ($arrayimage["type"] == "image/jpeg")
|| ($arrayimage["type"] == "image/jpg")
|| ($arrayimage["type"] == "image/pjpeg")
|| ($arrayimage["type"] == "image/x-png")
|| ($arrayimage["type"] == "image/png"))
//check image size
&& ($arrayimage["size"] < 20000000)
//check iamge extension in above created extension array
&& in_array($extension, $allowedExts))
{
if ($arrayimage["error"] > 0)
{
echo "Error: " . $arrayimage["error"] . "<br>";
}
else
{
echo "Upload: " . $arrayimage["name"] . "<br>";
echo "Type: " . $arrayimage["type"] . "<br>";
echo "Size: " . ($arrayimage["size"] / 1024) . " kB<br>";
echo "Stored in: ".$arrayimage['tmp_name']."<br>";
//check if file is exist in folder of not
if (file_exists($dir."/".$arrayimage["name"]))
{
echo $arrayimage['name'] . " already exists. ";
}
else
{
//extracting database fields and value
foreach($fields as $key=>$val)
{
$f[]=$key;
$v[]=$val;
$fi=implode(",",$f);
$value=implode("','",$v);
}
//dynamic sql for inserting data into any table
$sql="INSERT INTO " . $table ."(".$fi.") VALUES ('".$value."')";
//echo $sql;
$imginsquery=mysql_query($sql);
move_uploaded_file($arrayimage["tmp_name"],$dir."/".$arrayimage['name']);
echo "<br> Stored in: " .$dir ."/ Folder <br>";
}
}
}
//if file not match with extension
else
{
echo "Invalid file";
}
}
//function imageUpload ends here
}
//imageFunctions class ends here
//imageFunctions 类到此结束
you can try this code for inserting multiple images with its extension this function is created for checking image files you can replace the extension list for perticular files in the code
您可以尝试使用此代码插入多个带有扩展名的图像 此功能是为检查图像文件而创建的 您可以替换代码中特定文件的扩展名列表
回答by damko
partial answer: pear HTTP_UPLOAD can be usefull http://pear.php.net/manual/en/package.http.http-upload.examples.php
部分答案:梨 HTTP_UPLOAD 可能有用 http://pear.php.net/manual/en/package.http.http-upload.examples.php
there is a full example for multiple files
有多个文件的完整示例

