使用class.upload.php上传多个文件和标题

时间:2017-01-01 17:16:22

标签: php mysqli image-uploading

我目前在使用class.upload.php上传图片时插入字幕时遇到问题。

图像重命名效果很好,但所有图像都有相同的标题,尽管我为每个图像设置了单独的文本框。

代码:

<form action="" enctype="multipart/form-data" id="form" method="post" name="form" role="form">
  <table>
    <tr>
      <td><input class="form-control" id="customFieldValue2" name="photo_title[]" type="text"></td>
      <td><input class="form-control" id="customFieldName2" name="image_field[]" type="file"></td>
    </tr>
    <tr>
      <td><input class="form-control" id="customFieldValue2" name="photo_title[]" type="text"></td>
      <td><input class="form-control" id="customFieldName2" name="image_field[]" type="file"></td>
    </tr>
  </table>
</form>

处理器:

$files = array();
                foreach ($_FILES['image_field'] as $k => $l) {                      
                 foreach ($l as $i => $v) {
                 if (!array_key_exists($i, $files))
                   $files[$i] = array();
                   $files[$i][$k] = $v;
                 }
                }
                    $hitung=0;
                    foreach ($files as $file) 
                    {
                        $handle = new Upload($file);
                        if ($handle->uploaded) 
                        { 
                            $hitung++;
                            $newname = $t_timestamp."_".$hitung;
                            $handle->file_new_name_body = $newname;
                            $handle->Process("../uploaded/");     
                            if ($handle->processed) 
                            {
                                $filename=$newname.".jpg";
                                $query ="INSERT INTO tbl_report_photos SET 
                                photo_title='".$filename."',
                                photo_link='".$filename."',
                                photo_unique='".$aid."'";

                                if ($sql = mysqli_query($con,$query)) 
                                {
                                    echo "<script>alert('Report Updated');window.location.href='index.php';</script>";
                                }     
                            }   
                            else 
                            {
                                echo 'Error: ' . $handle->error;     
                            }   
                        } 
                        else 
                        {     
                            echo 'Error: ' . $handle->error;   
                        }   
                        unset($handle); 
                    }

我编辑了代码。它有一个较少的循环

1 个答案:

答案 0 :(得分:0)

你拥有相同标题的原因在于它自己的循环,它不是在排列变量,而是覆盖自身。使它成为一个数组,然后写相应的键:

$taitel[$i] = $_POST['photo_title'][$i];

你有很多循环,很难建议把它放在你的剧本中。

编辑:由于您在设置此问题时遇到问题,我将进行演示。我可能会尝试一些事情。一,我将创建一个文件观察者和两个,创建一个上传类的扩展类。那个看起来有点尴尬:

<强> UploadObserver.php

/*
**  @description    This will take over for a couple of pieces of your script
*/
class UploadObserver
    {
        private $Upload;
        /*
        **  @description    Pass your database. I like PDO and know it better so I am using that connection
        **                  You would have to change this to accept your MySQLi connection
        */
        public  function __construct(\PDO $con)
            {
                $this->con  =   $con;
            }
        /*
        **  @description    Create a new instance of a version of the Upload class
        */
        public  function upload($file)
            {
                # Create a new instance of our extended class
                $this->Upload   =   new \PowerUpload($file);
                # Return it for use
                return $this->Upload;
            }
        /*
        **  @description    This is the class that will process the files array
        */
        public  function getFiles($key = 'image_field')
            {
                $files  =   array();
                foreach ($_FILES[$key] as $k => $l) {                      
                    foreach ($l as $i => $v) {
                        if (!array_key_exists($i, $files))
                            $files[$i]      =   array();

                        $files[$i][$k]  =   $v;
                    }
                }
                # Send back formatted array
                return $files;
            }
        /*
        **  @description    Checks to see if the files array has files
        */
        public  function filesSet($key = 'image_field')
            {
                return (!empty($_FILES[$key]));
            }
        /*
        **  @description    This will write the row to your database
        */
        public  function saveToDb($settings)
            {
                # Make sure to prepare and bind your values just in case
                $sql ="INSERT INTO tbl_report_photos SET 
                photo_title = ?,
                photo_link = ?,
                photo_unique = ?";

                $query  =   $this->con->prepare($sql);
                $query->execute($settings);
            }
        /*
        **  @description    You could store this in a View class, but for sake of ease I included it here
        */
        public  function getSuccess()
            {
                ob_start();
            ?>  
            <script>
                alert('Report Updated');
                window.location.href = 'index.php';
            </script>
            <?php
                $data   =   ob_get_contents();
                ob_end_clean();

                return $data;
            }
    }

<强> upload.php的

根据您在示例中演示的内容,这只是猜测这个类的外观。

class Upload
    {
        public  $uploaded,
                $file_new_name_body,
                $processed,
                $error;

        protected   $filename,
                    $fileArray;

        public  function __construct($fileArray)
            {
                $this->fileArray    =   $fileArray;
            }

        public  function process($path)
            {
                if(!is_dir($path))
                    mkdir($path,0755,true);

                if(empty($this->file_new_name_body))
                    $this->file_new_name_body   =   $this->fileArray['name'];

                $this->error        =   $this->fileArray['error'];
                $this->processed    =   move_uploaded_file($this->fileArray['tmp_name'],str_replace('//','/',$path.'/'.$this->file_new_name_body));

                if(!$this->processed)
                    throw new \Exception("File was unable to upload.");
            }
    }

<强> PowerUpload.php

/*
**  @description    If you can, I would extend the Upload class and save some more readable methods to it
*/
class PowerUpload extends Upload
    {
        public  function setNewFile($fileArray)
            {
                $this->fileArray    =   $fileArray;
                return $this;
            }

        public  function setFileName($name)
            {
                $this->file_new_name_body   =   $name;

                return $this;
            }

        public  function checkHasUploaded()
            {
                $files  =   (!empty($this->fileArray));

                if(!$files)
                    throw new \Exception("File array can not be empty.");

                return $files;
            }

        public  function hasProcessed()
            {
                return $this->processed;
            }

        public  function processUpload($path)
            {
                $this->process($path);
            }

        public  function getError()
            {
                return $this->error;
            }
    }

基于更改的修改脚本:请注意,表单输入名称具有实际键值,因此您可以更轻松地将文件与名称匹配。

# Create the upload observer, $con is your database connection
$Uploader       =   new UploadObserver($con);
# If there are files uploading
if($Uploader->filesSet()) {
    # Create a loop from the new array
    # Keep the $key value to match it up with the files value
    foreach($Uploader->getFiles() as $key => $file) {
        # Use a try because the uploader submits exceptions on failures
        try {
            # Set the name
            $newname    =   $t_timestamp."_".$key;
            # Tag on the extension
            $filename   =   $newname.".jpg";
            # Create the upload instance
            $handle     =   $Uploader->upload($file);
            # This will throw exception if failed
            $handle->checkHasUploaded();
            # Assign the file name and upload the file to folder
            $handle->setFileName($newname)->processUpload(realpath(__DIR__.'/..').'/uploaded/');
            # Save the file info to your database using the connection passed originally
            # You should throw exception here on database fail, PDO does it automatically so it's caught
            $Uploader->saveToDb(array($_POST['photo_title'][$key],$filename,$aid));
            # Create javascript view
            echo $Uploader->getSuccess();
        }
        # Catch error(s) from the non-db classes    
        catch(\Exception $e) {
            echo 'Error: '.$e->getMessage();
        }
        # Catch error(s) from the db classes
        catch(\PDOException $e) {
            echo 'Error: '.$e->getMessage();
        }
    }
}
?>
<form method="post" enctype="multipart/form-data" action="<?php echo $this->getDataNode('_SERVER')->REQUEST_URI ?>">
    <table>
        <tr>
            <td><input class="form-control" id="customFieldValue2" name="photo_title[1]" type="text"></td>
            <td><input class="form-control" id="customFieldName2" name="image_field[1]" type="file"></td>
        </tr>
        <tr>
            <td><input class="form-control" id="customFieldValue2" name="photo_title[2]" type="text"></td>
            <td><input class="form-control" id="customFieldName2" name="image_field[2]" type="file"></td>
        </tr>
    </table>
    <input type="submit" value="SAVE" />
</form>