【问题标题】:multi image upload wrong quantity on file-upload文件上传时多张图片上传数量错误
【发布时间】:2012-04-16 07:38:34
【问题描述】:

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

$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)) {

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

【问题讨论】:

    标签: php mysql image file-upload move


    【解决方案1】:

    首先,我将分别命名上传的字段。例如。将第一个字段命名为 <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

    这些有帮助吗?

    【讨论】:

    • 他正在使用 HTML5 <input type="file" name="image" multiple="multiple" />,所以他以那种格式获取它们。
    • 你好,谢谢或回答。问题是我不能轻易命名每个字段,因为这个输入字段是由一个函数创建的。
    【解决方案2】:

    您的代码非常适合我在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>
    

    【讨论】:

    • 您需要做的就是更新问题而不是创建另一个问题...@bonny
    • 它没有增长,因为您接受了一个答案但没有表明您仍然有问题......当您编辑和添加新信息时,每个人都会知道并看看他们可以做什么,直到问题得到解决...... .
    • 该功能应该在同一个页面中............我会编辑它,以便您了解如何使用它......
    • 另存为test.php 运行它并在此处粘贴您得到的确切错误或输出...
    • 我想我知道您遇到了问题...PHP SAVE MODE 1. 您不必在该路径中创建文件夹a/b/c/d/tmp_image 2. 如果您有权访问php.ini 设置@ 987654328@ 或者你可以使用.htaccess 并把它放在那里php_value safe_mode "1" .. 你应该有一个工作脚本...
    【解决方案3】:

    您为什么将$_FILES 超全局数组作为一个三维数组访问?

    如果您想要从&lt;input type="file" name="image"/&gt; 上传的文件的文件名,您只需$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', ... ]
    }
    

    【讨论】:

    • 他正在使用 HTML5 &lt;input type="file" name="image" multiple="multiple" /&gt;,所以他以那种格式获取它们。
    • 我使用它是因为我喜欢为每个文件显示明确的错误消息。
    【解决方案4】:

    我不确定这是否可以为您解决问题,但您可以尝试将这些转换为“正常”$_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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 2019-05-17
      相关资源
      最近更新 更多