多图像上传文件上传错误的数量

时间:2012-04-16 07:38:35

标签: php mysql image file-upload move

我想借助数组将一些图像上传到目录。因此我有这个代码:

$allowedExtensions = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
            $maxSize = 2097152;
            $Dir = "a/b/c/d";
            $storageDir = "a/b/c/d/tmp_images";

            //Arrays
            $errors2 = $output = array();


            if(!empty($_FILES['image'])){  

            // Validation loop (I prefer for loops for this specific task)
            for ($i = 0; isset($_FILES['image']['name'][$i]); $i++) {

                $fileName = $_FILES['image']['name'][$i];
                $fileSize = $_FILES['image']['size'][$i];
                /*$fileErr = $_FILES['image']['error'][$i];*/
                $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

                // Dateiendung überprüfen
                if (!in_array($fileExt, $allowedExtensions)) {
                    $errors2[$fileName][] = "format $fileExt in $fileName is not accepted";
                }

                // check filesize
                if ($fileSize > $maxSize) {
                    $errors2[$fileName][] = "maxsize of 2MB exceeded";
                }


            }

            /*// Handle validation errors here
            if (count($errors) > 0) {
                echo "Fehler beim Upload des Bildmaterials:"; 
                echo ($errors); ->gibt "Array" aus
            }*/


            if (is_dir($Dir)){
                mkdir($storageDir, 0755);
            }else{
                mkdir($Dir, 0755);
                mkdir($storageDir, 0755);
            }


            // Fileupload
            for ($i = 0; isset($_FILES['image']['name'][$i]); $i++) {

            // Get base info
            $fileBase = basename($_FILES['image']['name'][$i]);
            $fileName = pathinfo($fileBase, PATHINFO_FILENAME);
            $fileExt = pathinfo($fileBase, PATHINFO_EXTENSION);
            $fileTmp = $_FILES['image']['tmp_name'][$i];

            // Construct destination path
            $fileDst = $storageDir.'/'.basename($_FILES['image']['name'][$i]);
            for ($j = 0; file_exists($fileDst); $j++) {
                $fileDst = "$storageDir/$fileName-$j.$fileExt";
            }

            // Move the file 

            if (count($errors2) == 0) { 
                if (move_uploaded_file($fileTmp, $fileDst)) {
                                    ...
                                }
                        }

该代码的问题如下:如果上传两个或多个带有已接受结尾的文件,它将回显:

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to access abc2.png in /a/b/xxx.php on line xxx

指的是那条线:

if (move_uploaded_file($fileTmp, $fileDst)) {

除第一张照片外,每张照片都会显示此消息。所以我不知道我做错了什么。如果有人可以帮助我,我真的很感激。我真的很感激。非常感谢。

4 个答案:

答案 0 :(得分:2)

首先,我会将上传的字段分别命名。例如。将第一个字段命名为<input name="image_1" type="file" />,将第二个字段命名为<input name="image_2" type="file" />。然后,您可以迭代$_FILES数组:

foreach($_FILES as $fileId => $file){
    //make sure it's a file you want (optional)
    if(!preg_match("/^image\_\d+$/",$fileId){
         continue;
    }

    //the rest of your code from the for loop
}

其次,您需要确保您的表单的enctype为multipart/form-data

这有什么帮助?

答案 1 :(得分:1)

为什么要将$_FILES超全球数组作为三维数组访问?

如果您想要从<input type="file" name="image"/>上传文件的文件名,您只需要$name = $_FILES[ 'image' ][ 'name' ],最后就不需要[ $i ]

您需要循环遍历$ _FILES中的条目,如下所示:

foreach ( $_FILES as $inputName => $fileData )
{
    // $inputName is be 'image` for the first input and so on,
    // $fileData will be an array of the attributes [ 'name', 'tmp_name', ... ]
}

答案 2 :(得分:1)

我不确定这是否可以为您解决,但您可以尝试将这些转换为“正常”$_FILES值。

$arr_files  =   @$_FILES['image'];

$_FILES     =   array();
foreach(array_keys($arr_files['name']) as $h)
$_FILES["image_{$h}"]    =   array(  'name'      =>  $arr_files['name'][$h],
                                    'type'      =>  $arr_files['type'][$h],
                                    'tmp_name'  =>  $arr_files['tmp_name'][$h],
                                    'error'     =>  $arr_files['error'][$h],
                                    'size'      =>  $arr_files['size'][$h]);

然后像平常一样运行循环。

See previous related answer

答案 3 :(得分:1)

我的答案limiting the checking condition while uploading swf files

,我的答案非常similar

这就是你应该如何实现这个......

完整脚本

<?php
error_reporting ( E_ALL );
$allowedExtensions = array (
        'jpg',
        'jpeg',
        'png',
        'bmp',
        'tiff',
        'gif' 
);
$maxSize = 2097152;
$dirImage = "photos/tmp_images";
$errors = $output = array ();
if (isset ( $_FILES ['image'] )) {
    foreach ( $_FILES ['image'] ['tmp_name'] as $key => $val ) {

        $fileName = $_FILES ['image'] ['name'] [$key];
        $fileSize = $_FILES ['image'] ['size'] [$key];
        $fileTemp = $_FILES ['image'] ['tmp_name'] [$key];

        $fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
        $fileExt = strtolower ( $fileExt );

        if (empty ( $fileName ))
            continue;

            // Dateiendung überprüfen
        if (! in_array ( $fileExt, $allowedExtensions )) {
            $errors [$fileName] [] = "format $fileExt in $fileName is not accepted";
        }

        if ($fileSize > $maxSize) {
            $errors [$fileName] [] = "maxsize of 2MB exceeded";
        }

        if (! mkdir_recursive ( $dirImage, 0777 )) {
            $errors [$fileName] [] = "Error  Creating /Writing  Directory $dirImage ";
        }

        // Construct destination path
        $fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;
        $filePrifix = basename ( $fileName, "." . $fileExt );
        $i = 0;
        while ( file_exists ( $fileDst ) ) {
            $i ++;
            $fileDst = $dirImage . DIRECTORY_SEPARATOR . $filePrifix . "_" . $i . "." . $fileExt;

        }
        // Move the file

        if (count ( $errors ) == 0) {
            if (move_uploaded_file ( $fileTemp, $fileDst )) {
                // ...

                $output [$fileName] = "OK";
            }
        }

    }
}

function mkdir_recursive($pathname, $mode) {
    is_dir ( dirname ( $pathname ) ) || mkdir_recursive ( dirname ( $pathname ), $mode );
    return is_dir ( $pathname ) || mkdir ( $pathname, $mode );
}
if (! empty ( $errors )) {
    echo "<pre>";
    foreach ( $errors as $file => $error ) {
        echo $file, PHP_EOL;
        echo "==============", PHP_EOL;
        foreach ( $error as $line ) {
            echo $line, PHP_EOL;
        }
        echo PHP_EOL;
    }
    echo "</pre>";
}

if (! empty ( $output )) {
    echo "<pre>";
    echo "Uploaded Files", PHP_EOL;
    foreach ( $output as $file => $status ) {
        echo $file, "=", $status, PHP_EOL;
    }

    echo "</pre>";
}
?>


<form method="post" enctype="multipart/form-data">
    <label for="file">Filename 1:</label> <input type="file" name="image[]"
        id="file" /> <br /> <label for="file">Filename 2:</label> <input
        type="file" name="image[]" id="file" /> <br /> <label for="file">Filename
        3:</label> <input type="file" name="image[]" id="file" /> <br /> <input
        type="submit" name="submit" value="Submit" />
</form>