当我需要多个文件时,PHP仅上传一个文件

时间:2019-02-24 11:15:15

标签: php for-loop file-upload foreach upload

我需要对上传的每个文件运行以下代码:

$uploads_dir = 'tdump';
    $tmp_name = $_FILES['upfiles']["tmp_name"];
    $name = basename($_FILES['upfiles']["name"]);
    move_uploaded_file($tmp_name, "$uploads_dir/$name");
    $filename="$uploads_dir/$name";
    echo "$filename";
    $mp3file=new CMP3File;
    $mp3file->getid3($filename);
    echo "Title: $mp3file->title<br>\n";
    echo "Artist: $mp3file->artist<br>\n";
    echo "Album: $mp3file->album<br>\n";
    echo "Year: $mp3file->year<br>\n";
    echo "Comment: $mp3file->comment<br>\n";
    echo "Genre: " . Ord($mp3file->genre) . "<br>\n";

到目前为止,我已经尝试过:

$total = count($_FILES['upfiles']['name']);
print_r($total);
for ($i=0; $i < $total; $i++){
    $uploads_dir = 'tdump';
    $tmp_name = $_FILES['upfiles']["tmp_name"];
    $name = basename($_FILES['upfiles']["name"]);
    move_uploaded_file($tmp_name, "$uploads_dir/$name");
    $filename="$uploads_dir/$name";
    echo "$filename";
    $mp3file=new CMP3File;
    $mp3file->getid3($filename);
    echo "Title: $mp3file->title<br>\n";
    echo "Artist: $mp3file->artist<br>\n";
    echo "Album: $mp3file->album<br>\n";
    echo "Year: $mp3file->year<br>\n";
    echo "Comment: $mp3file->comment<br>\n";
    echo "Genre: " . Ord($mp3file->genre) . "<br>\n";
}

html代码:

<form method="post">
    <input name="upfiles[]" type="file" multiple/>
    <input type="submit" name="send">
</form>

mp3file变量是getid3库,请不要关注它。在整个代码中,我无法弄清楚的是如何循环浏览每个上载的文件,获取文件名并保存。我认为应该是for或foreach循环。

3 个答案:

答案 0 :(得分:0)

for($i=0; $i<your_no_of_files; $i++)
{
    $tmp_name = $file["tmp_name"];
$name = basename($file["name"]).$i;
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$filename="$uploads_dir/$name";
echo "$filename";
$mp3file=new CMP3File;
$mp3file->getid3($filename);
echo "Title: $mp3file->title<br>\n";
echo "Artist: $mp3file->artist<br>\n";
echo "Album: $mp3file->album<br>\n";
echo "Year: $mp3file->year<br>\n";
echo "Comment: $mp3file->comment<br>\n";
echo "Genre: " . Ord($mp3file->genre) . "<br>\n";
}**MAYBE THIS WILL WORK**

答案 1 :(得分:0)

HTML示例:

    <input type="file" name="filename[]">
    <input type="file" name="filename[]">
    ....
    <input type="file" name="filename[]">

尝试这样做,而不要使用“文件名”。

PHP示例:

  if ($_FILES){
        for ($i = 0; $i < count($_FILES['filename']['name']); $i++) {

            //......
            $tmp_name = $_FILES['filename']["tmp_name"][$i];
            //......

        }
    }

答案 2 :(得分:0)

在表单部分中,编辑以下属性

<input name="userfile[]" type="file" />

此userfile数组会将您的所有文件存储在一个数组中。

然后使用count()函数显示元素编号。

例如

$no_of_files=count($_FILES['userfile']['tmp_name']);