使用PHP类上传多个图像

时间:2017-10-11 06:36:45

标签: php image class

我需要查询我正在使用PHP类上传单个图像。下面我有上传图片的类和PHP代码。它适用于单个图像上传,现在我想使用相同的类上传多个图像,我用于此目的的循环,它给出了一些错误。请简要说明我做错了什么

多个图片的HTML

<input type="file" name="photo[]" placeholder="Photo">

多个图像的代码

for($i=0;$i<$count;$i++ ) {
        if(isset($_FILES['photo']['tmp_name'][$i]) && ($_FILES['photo']['tmp_name'][$i]!="")){
            $uploadImage = new UploadImage;
            echo $uploadImage->upload('photo', null, '../uploads/', 150, 0, '../uploads/thumb/', 75, 75);
    }
          }
  

以下代码适用于单张图片上传,工作正常。

HTML

<input type="file" name="photo" placeholder="Photo">

代码

if(isset($_FILES['photo']['tmp_name']) && ($_FILES['photo']['tmp_name']!="")){
            $uploadImage = new UploadImage;
            $obj['image'] = $uploadImage->upload('photo', null, '../uploads/', 150, 0, '../uploads/thumb/', 75, 75);
        }

Class.php

<?php
class UploadImage {
    public function upload($imageField, $imageFieldIndex = null, $strLargePath = null, $largeWidth = 0, $largeHeight = 0, $strThumbPath = null, $thumbWidth = 0, $thumbHeight = 0)
    {
        $noLarge = false;
        $noThumb = false;

        if(empty($strLargePath)) {
            $noLarge = true;
        }

        if(empty($strThumbPath)) {
            $noThumb = true;
        }


    echo   $fileName = isset($imageFieldIndex) ? stripslashes($_FILES[$imageField]['name'][$imageFieldIndex]) : stripslashes($_FILES[$imageField]['name']);
       $fileTempName = isset($imageFieldIndex) ? $_FILES[$imageField]['tmp_name'][$imageFieldIndex] : $_FILES[$imageField]['tmp_name'];

        $extension = $this->getExtension($fileName);

        $imageName = time().$imageFieldIndex.'.'.$extension;

        if($noLarge == false) {
            $this->resize($largeWidth, $largeHeight, $fileTempName, $imageName, $strLargePath);
        }

        if($noThumb == false) {
            $this->resize($thumbWidth, $thumbHeight,$fileTempName, $imageName, $strThumbPath);
        }
        return $imageName;
    }

    private function getExtension($strInput) 
    {
        $i = strrpos($strInput,".");
        if (!$i){return null;}

        $j = strlen($strInput) - $i;
        $output = substr($strInput, $i + 1, $j);
        return $output;
    }

    private function resize($newWidth, $newHeight, $imageTempName, $imageName, $savePath) {
        $image = new ResizeImage;
        $image->newWidth = $newWidth;
        $image->newHeight = $newHeight;

        $image->imageTempName = $imageTempName; // Full Path to the file

        $image->ratio = true; // Keep Aspect Ratio?

        // Name of the new image (optional) - If it's not set a new will be added automatically

        $image->imageName = substr($imageName, 0, strrpos($imageName, '.'));

        /* Path where the new image should be saved. If it's not set the script will output the image without saving it */

        $image->savePath = $savePath;

        $process = $image->resize();

        if($process['result'] && $image->savePath)
        {
            //echo 'The new image ('.$process['new_file_path'].') has been saved.';
        }
    }
}

/*-------------------------------- Image resize Class -----------------------------------------*/
class ResizeImage {

    var $imageTempName;
    var $newWidth;
    var $newHeight;
    var $ratio;
    var $imageName;
    var $savePath;

    function resize(){
        if(!file_exists($this->imageTempName)){
          exit("File ".$this->imageTempName." does not exist.");
        }

        $info = GetImageSize($this->imageTempName);

        if(empty($info)){
          exit("The file ".$this->imageTempName." doesn't seem to be an image.");   
        }

        $width = $info[0];
        $height = $info[1];
        $mime = $info['mime'];

        /* Keep Aspect Ratio? */
        $this->ratio = true;
        if($this->ratio){
            $thumb = ($this->newWidth < $width && $this->newHeight < $height) ? true : false; // Thumbnail
            $largeImage = ($this->newWidth >= $width || $this->newHeight >= $height) ? true : false; // Large Image
            if($thumb){
                if($this->newWidth > $this->newHeight){
                    $x = ($width / $this->newWidth);
                    $this->newHeight = ($height / $x);
                }else {
                    $x = ($height / $this->newHeight);
                    $this->newWidth = ($width / $x);
                }
            }else if($largeImage){
                if($this->newWidth >= $width){
                    $x = ($this->newWidth / $width);
                    $this->newHeight = ($height * $x);
                }
                else if($this->newHeight >= $height){
                    $x = ($this->newHeight / $height);
                    $this->newWidth = ($width * $x);
                }
            }
        }

        // What sort of image?

        $type = substr(strrchr($mime, '/'), 1);

        switch ($type){
            case 'jpeg':
                $image_create_func = 'ImageCreateFromJPEG';
                $image_save_func = 'ImageJPEG';
                $newImageExt = 'jpg';
                break;

            case 'jpg':
                $image_create_func = 'ImageCreateFromJPEG';
                $image_save_func = 'ImageJPEG';
                $newImageExt = 'jpg';
                break;

            case 'png':
                $image_create_func = 'ImageCreateFromPNG';
                $image_save_func = 'ImagePNG';
                $newImageExt = 'png';
                break;

            case 'bmp':
                $image_create_func = 'ImageCreateFromBMP';
                $image_save_func = 'ImageBMP';
                $newImageExt = 'bmp';
                break;

            case 'gif':
                $image_create_func = 'ImageCreateFromGIF';
                $image_save_func = 'ImageGIF';
                $newImageExt = 'gif';
                break;

            case 'vnd.wap.wbmp':
                $image_create_func = 'ImageCreateFromWBMP';
                $image_save_func = 'ImageWBMP';
                $newImageExt = 'bmp';
                break;

            case 'xbm':
                $image_create_func = 'ImageCreateFromXBM';
                $image_save_func = 'ImageXBM';
                $newImageExt = 'xbm';
                break;

            default: 
                $image_create_func = 'ImageCreateFromJPEG';  
                $image_save_func = 'ImageJPEG';
                $newImageExt = 'jpg';
            }
            // New Image
            $image_c = imagecreatetruecolor($this->newWidth, $this->newHeight);
            $newImage = $image_create_func($this->imageTempName);
            imagealphablending($image_c, false);
            imagesavealpha($image_c,true);
            $transparent = imagecolorallocatealpha($image_c, 255, 255, 255, 127);
            imagefilledrectangle($image_c, 0, 0, $this->newWidth, $this->newHeight, $transparent);

            ImageCopyResampled($image_c, $newImage, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $width, $height);

                if($this->savePath)
                {
                   if($this->imageName)
                   {
                    $new_name = $this->imageName.'.'.$newImageExt;
                   }
                   else
                   {
                    $new_name = $this->newImageName(basename($this->imageTempName)).'_resized.'.$newImageExt;
                   }

                $save_path = $this->savePath.$new_name;
                }
                else
                {
                /* Show the image without saving it to a folder */
                   header("Content-Type: ".$mime);

                   $image_save_func($image_c);

                   $save_path = '';
                }

                $process = $image_save_func($image_c, $save_path);

                return array('result' => $process, 'new_file_path' => $save_path);

            }

        function newImageName($filename)
        {
            $string = trim($filename);
            $string = strtolower($string);
            $string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));
            $string = ereg_replace("[ \t\n\r]+", "_", $string);
            $string = str_replace(" ", '_', $string);
            $string = ereg_replace("[ _]+", "_", $string);

            return $string;
        }
}
?>

2 个答案:

答案 0 :(得分:2)

将图像索引添加到上传功能

for($i=0;$i<$count;$i++ ) {
        if(isset($_FILES['photo']['tmp_name'][$i]) && ($_FILES['photo']['tmp_name'][$i]!="")){
            $uploadImage = new UploadImage;
            echo $uploadImage->upload('photo', $i, '../uploads/', 150, 0, '../uploads/thumb/', 75, 75);
           //...................................^ here
    }
}

答案 1 :(得分:1)

我认为这是可行的方式。

<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="userfile[]" type="file" /><br />
  <input name="userfile[]" type="file" /><br />
  <input type="submit" value="Send files" />
</form>

对于脚本,您可以使用数组上传多个文件。

Array
(
    [0] => Array
        (
            [name] => foo.txt
            [type] => text/plain
            [tmp_name] => /tmp/phpYzdqkD
            [error] => 0
            [size] => 123
        )

    [1] => Array
        (
            [name] => bar.txt
            [type] => text/plain
            [tmp_name] => /tmp/phpeEwEWG
            [error] => 0
            [size] => 456
        )
)

将$ _FILES数组转换为清除器(IMHO)数组的快速函数。

<?php

function reArrayFiles(&$file_post) {

    $file_ary = array();
    $file_count = count($file_post['name']);
    $file_keys = array_keys($file_post);

    for ($i=0; $i<$file_count; $i++) {
        foreach ($file_keys as $key) {
            $file_ary[$i][$key] = $file_post[$key][$i];
        }
    }

    return $file_ary;
}

?>

现在我可以执行以下操作:

<?php

if ($_FILES['upload']) {
    $file_ary = reArrayFiles($_FILES['ufile']);

    foreach ($file_ary as $file) {
        print 'File Name: ' . $file['name'];
        print 'File Type: ' . $file['type'];
        print 'File Size: ' . $file['size'];
    }
}

?>

前往here获取更多解释。