0

我喜欢在数组的帮助下将一些图像上传到目录。因此我有这个代码:

$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

4 回答 4

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.

这有什么帮助吗?

于 2012-04-16T07:46:19.253 回答
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', ... ]
}
于 2012-04-16T07:48:18.690 回答
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]);

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

查看之前的相关答案

于 2012-04-16T08:25:02.460 回答
1

您的代码非常similar符合我在上传 swf 文件时限制检查条件的回答

这就是你应该如何实现这样的..

完整脚本

<?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>
于 2012-04-16T08:38:12.363 回答