使用 FormData 和 Zend Framework 2 检查数组是否为空

Checking if a array isn't empty with FormData and Zend Framework 2

我正在尝试查看从 FormData javascript 发送的数组是否不为空,如果不是,则使用该数组创建目录并上传文件。它在控制台中显示为一个普通数组,其中包含 $_FILES 中的所有索引,但由于某种原因它在 PHP 端不起作用。这是与此相关的代码:

型号 -

public function postStatus($status, array $image = array())
{
    if (empty($status)) {
        throw new StatusException("Status text cannot be left empty.");
    } else {
        // get the user's id based on $this->user
        $this->select->columns(array('id'))
        ->where(array('username' => $this->user));

        $query = $this->sql->getAdapter()->query(
            $this->sql->buildSqlString($this->select),
            Adapter::QUERY_MODE_EXECUTE
        );

        if ($query->count() > 0) {
            foreach ($query as $result) {
                $row = $result;
            }

            $select = $this->gateway->select(array('id' => $row['id']));

            if ($select->count() > 0) {
                // update status
                $update_data = array(
                    'status' => $status,
                );

                $update = $this->gateway->update($update_data, array('id' => $row['id']));

                if ($update > 0) {
                    return true;
                } else {
                    throw new StatusException("Error posting status.");
                }
            } else {
                // insert status
                $insert_data = array(
                    'id'     => $row['id'],
                    'status' => $row['status'],
                );

                $insert = $this->gateway->insert($insert_data);

                if ($insert > 0) {
                    // put image into status folder
                    if (count($image) > 0) { // this is the culprit I believe
                        if (!is_dir(getcwd() . '/public/images/profile/' . $this->user . '/status')) {
                            // make the status directory
                            // then insert any images if found
                            mkdir(getcwd() . '/public/images/profile/' . $this->user . '/status');

                            if (is_uploaded_file($image['tmp_name'])) {
                                move_uploaded_file($image['tmp_name'], getcwd() . '/public/images/profile/' . $this->user . '/status/' . $image['name']);
                                return true;
                            } else {
                                throw new StatusException("Error uploading your image for your status.");
                            }
                        } else {
                            // insert any images if found
                            if (is_uploaded_file($image['tmp_name'])) {
                                move_uploaded_file($image['tmp_name'], getcwd() . '/public/images/profile/' . $this->user . '/status/' . $image['name']);
                                return true;
                            } else {
                                throw new StatusException("Error uploading your image for your status.");
                            }
                        }
                    } 

                    // no image
                    return true;
                } else {
                    throw new StatusException("Error posting status.");
                }
            }
        } else {
            throw new StatusException("Invalid username passed.");
        }
    }
}

传递的数组如下:

name: "boned.jpg", type: "image/jpeg", tmp_name: "C:\xampp\tmp\php3684.tmp", error: 0, size: 25388

如您所见,数组不为空,但模型中的代码并未创建目录和上传文件。我检查了错误日志,它没有说明有关创建目录或上传文件的任何内容,所以我不确定发生了什么。

哦,我正在使用 FormData 进行 jquery ajax 调用,以防万一,这是它的代码

$('#post-status').on('click', function() {
   if ($('#status').html() != "Status: " && $('#status').html() != "") {
       var status = $('#status').html();

       var getstatus;
       var getfile;

       var formData = new FormData();

       if (document.getElementById('status-photo') == null) {
           formData.append("statustext", status);

           getstatus = formData.get("statustext");
       } else {
           formData.append("statustext", status);
           formData.append("userfile", document.getElementById('status-photo').files[0]);

           var getstatus = formData.get("statustext");
           var getfile = formData.get("userfile");
       }


       $('#status-msg').html("");

       $.ajax({
           type: "POST",
           contentType: false,
           processData: false,
           url: "/members/status/post-status",
           dataType: "json",
           data: formData
       }).done(function(msg) {
           console.log(msg);
           $('#status-msg').html(msg.success);
           $('#status').html('Status: ');

           $('#added-status-photos').attr('style', 'display: none;');
           $('#delete-include-pic').attr('style', 'display: none;');

           $('#include-pic').attr('style', 'display: block;');

           // update status text
           $.getJSON('/members/status/get-status', function(stat) {
                $('#current-status').html("Current Status: " + stat.status);
           });
        }).fail(function(msg) {
            console.log(msg.fail);
            $('#status-msg').html(msg.fail);

            $('#added-status-photos').attr('style', 'display: none;');
            $('#delete-include-pic').attr('style', 'display: none;');

            $('#include-pic').attr('style', 'display: block;');
        }); 
    } else {
        $('#status-msg').html("Please enter a valid status.");
        return;
    }
});

任何帮助将不胜感激,因为这让我抓狂。

谢谢!

更新:

抱歉,我以为我输入了控制器代码,又来了:

public function poststatusAction()
{
    $layout = $this->layout();
    $layout->setTerminal(true);

    $view_model = new ViewModel();
    $view_model->setTerminal(true);

    if ($this->request->isPost()) {
        try {
            $status = $this->params()->fromPost('statustext');
            $file = $this->params()->fromFiles('userfile');

            if (count($file) > 0) {
                if ($this->getStatusService()->postStatus($status, $file)) {
                    echo json_encode(array('success' => 'Status updated'));
                } 
            } else {
                if ($this->getStatusService()->postStatus($status)) {
                    echo json_encode(array('success' => 'Status updated'));
                }
            }
        } catch (StatusException $e) {
            echo json_encode(array('fail' => $e->getMessage()));
        }
    }

    return $view_model;
}

我的评论可能不清楚,所以我把代码放在这里。您不需要这样做 $decoded = json_decode($image, true); 因为 $image 是 array 而不是 json.

if (! empty($image)) {
    if (! is_dir(getcwd() . '/public/images/profile/' . $this->user . '/status')) {
        // make the status directory
        // then insert any images if found
        mkdir(getcwd() . '/public/images/profile/' . $this->user . '/status');

        if (is_uploaded_file($image['tmp_name'])) {
            move_uploaded_file($image['tmp_name'], getcwd() . '/public/images/profile/' . $this->user . '/status/' . $image['name']);
            return true;
        } else {
            throw new StatusException("Error uploading your image for your status.");
        }
    } else {
        // insert any images if found
        if (is_uploaded_file($image['tmp_name'])) {
            move_uploaded_file($image['tmp_name'], getcwd() . '/public/images/profile/' . $this->user . '/status/' . $image['name']);
            return true;
        } else {
            throw new StatusException("Error uploading your image for your status.");
        }
    }
}

试着把代码改成这样,你就会确切地知道问题出在哪里了。在我看来,您没有创建目录的权限。

if (count($image) > 0) {
    $storeImagesDir = getcwd() . '/data/cache/' . $this->user . '/status';
    if (! is_dir($storeImagesDir)) {
        $dirCreated = mkdir($storeImagesDir,'0755', true);
        if(false === $dirCreated) {
            throw new StatusException("You don't have privileges to create the directory '.".$storeImagesDir."' for storing images.");
        } 
    }
    if (is_uploaded_file($image['tmp_name'])) {
        $imageMoved = move_uploaded_file($image['tmp_name'], $storeImagesDir.'/'. $image['name']);
        if(false === $imageMoved) {
            throw new StatusException("The uploaded image file cannot be moved.");
        }
        return true;
    } else {
        throw new StatusException("The uploaded image file is not found.");
    }
} else {
    throw new StatusException("Error posting status.");
}