PHP使用Optionals上传多个文件(至少需要2个文件中的1个)

时间:2017-07-19 16:19:40

标签: php forms file-upload

我正在尝试上传包含2个文件的表单,其中一个是.dae个对象,另一个是image。 表单(它在JS bootbox dialog内):

message:  '<form name="uploadForm" action="Control/upload.php" method="post" enctype="multipart/form-data"> '
                + '     Nome do objeto:<br />'
                + '     <input name="objectname" type="text"><br />'
                + '     <input type="hidden" name="MAX_FILE_SIZE" value="10000000">'
                + '     Objeto 3D(Formato <b>.dae</b>):<br />'
                + '     <input name="userfile[]" type="file" /><br />'
                + '     Imagem 2D do objeto(Formato <b>.png</b> ou <b>.jpg</b>) (<i>Opcional</i>):'
                + '     <input name="userfile[]" type="file" /><br />'
                + '     Comentário:<br />'
                + '     <textarea name="comment" rows="5" cols="75"></textarea>'
                + '</form>',

在表单中,有两个上传文件,“Objeto 3D”(3d对象,.dae)和“Imagem 2D do Objeto”(对象的图像2d,.jpg, .png) 有必要上传仅对象文件图片是可选的,因为如果没有上传,则数据库中有标准文件。

我试图让它工作创建一个布尔$ imageUploaded,它在getFileInputs方法中设置,但不知何故,它不能正常工作..

  • 如果我上传 a .dae和图片,则效果很好
  • 如果我上传错误的文件扩展名,它可以正常工作(2个错误或1个at 一次)
  • 但是,如果我只上传一个.dae文件,它就是我的错误 图片文件扩展名错误...

这是我的代码(它在其他脚本上运行)(没有数据库代码,这里不需要)

<?php 

    class UploadObject{
        //Control vars
        private $uploadIsOk;
        private $imageUploaded;

        //Input vars
        private $objectName;
        private $objectComment;
        private $uploadDir;
        private $uploadFiles;
        private $tmpFileNames;

        //Messages
        private $successMessage;
        private $errorMessage;


        public function __construct($uploadDir){
            $this->uploadIsOk = TRUE;
            $this->imageUploaded = FALSE;
            $this->successMessage = '';
            $this->errorMessage = '';

            $this->uploadDir = $uploadDir;
        }

        //Methods

        public function main(){
            $this->getTextInputs();
            $this->getFileInputs();

            $this->checkFileExtensions();
            if($this->getUploadIsOk()){
                $this->uploadTheFiles();
                $this->alertMessage($this->getSuccessMessage());
            }else{
                $this->alertMessage($this->getErrorMessage());
            }
        }

        public function uploadTheFiles(){
            $message = '';

            $this->replaceFileNames();

            if( move_uploaded_file( $this->getTmpFileNames()[0], $this->getUploadFiles()[0] ) ){
                $message = $message . "Upload do objeto foi realizado com sucesso;<br>";
                if($this->getImageUploaded()){

                    if( move_uploaded_file( $this->getTmpFileNames()[1], $this->getUploadFiles()[1] ) ){
                        $message = $message . "Upload da imagem do objeto foi realizado com sucesso;";
                    }

                }
                else{
                    $message = $message . "Imagem do objeto não foi enviada;";
                }
                $this->setSuccessMessage($message);
            }

        }

        public function getTextInputs(){
            if($_POST["objectname"] != "")
                $this->setObjectName($_POST["objectname"]);
            else 
                $this->setObjectName("objeto");
            $this->setObjectComment($_POST["comment"]);
        }

        public function getFileInputs(){
            $objectFile = $this->uploadDir . 'objects/' . basename($_FILES['userfile']['name'][0]);
            $imageFile = '';

            if($_FILES["userfile"]["name"][0] != ""){
                $imageFile = $this->uploadDir . 'images/' . basename($_FILES["userfile"]["name"][1]);
                $this->setImageUploaded(TRUE);
            }

            $uploadFiles = array($objectFile, $imageFile);

            $this->setUploadFiles($uploadFiles);

            $tmpObjectName = $_FILES["userfile"]["tmp_name"][0];
            if($this->getImageUploaded())
                $tmpImageName = $_FILES["userfile"]["tmp_name"][1];
            else
                $tmpImageName = "";

            $tmpFileNames = array($tmpObjectName, $tmpImageName);

            $this->setTmpFileNames($tmpFileNames);
        }

        public function checkFileExtensions(){
            $message = '';
            if(pathinfo( $this->getUploadFiles()[0], PATHINFO_EXTENSION ) != "dae"){
                $this->setUploadIsOk(FALSE);

                $message = $message . 'Erro: Objeto com formato inválido, utilize arquivos .dae;<br>';
            }
            if($this->getImageUploaded()){
                if(pathinfo( $this->getUploadFiles()[1], PATHINFO_EXTENSION ) != "jpg" && pathinfo( $this->getUploadFiles()[1], PATHINFO_EXTENSION ) != "jpeg" && pathinfo( $this->getUploadFiles()[1], PATHINFO_EXTENSION ) != "png"){
                    $this->setUploadIsOk(FALSE);

                    $message = $message . 'Erro: Imagem com formato inválido, utilize arquivos .jpg, .jpeg ou .png;';
                }
            }
            $this->setErrorMessage($message);

        }

        public function replaceFileNames(){
            date_default_timezone_set("Brazil/East");
            $data = date("h-i-sa-") . date("Y-m-d-");

            $fileName = $data . $this->getObjectName();

            $objectExtension = '.' . pathinfo($this->getUploadFiles()[0], PATHINFO_EXTENSION);
            $newObjectName = str_replace(basename($_FILES['userfile']['name'][0]), $fileName . $objectExtension, $this->getUploadFiles()[0]);

            $newImageName = '';
            if($this->getImageUploaded()){
                $imageExtension = '.' . pathinfo($this->getUploadFiles()[1], PATHINFO_EXTENSION);
                $newImageName = str_replace(basename($_FILES['userfile']['name'][1]), $fileName . $imageExtension, $this->getUploadFiles()[1]);
            }

            $uploadFiles = array($newObjectName, $newImageName);

            $this->setUploadFiles($uploadFiles);
        }

        public function alertMessage($message){

            $alertMessage = "<script >bootbox.alert({ message: '";

            $alertMessage = $alertMessage . $message;

            $alertMessage = $alertMessage . "', callback: function(){location.href='../index.php';} })</script>";

            echo $alertMessage;


        }

        //Getters and Setters
        ...
        ?>

无论如何,我是PHP新手,自己编写这段代码学习了一下,但是虽然这个问题无法工作......有人能告诉我哪里是我的错误吗?

1 个答案:

答案 0 :(得分:0)

您可以先使用 print_r($ _ FILES); 调试一下。比较单独上传.dae文件时获得的内容,以及上传.dae文件和图像时获得的内容。然后添加条件逻辑以使函数uploadTheFiles()跳过尝试上传图像(如果没有设置)。