使用FormData和Zend Framework 2

时间:2018-03-04 23:16:03

标签: php json zend-framework2

我正在尝试查看从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;
}

1 个答案:

答案 0 :(得分:1)

我的评论可能不太清楚,所以我将代码放在这里。您无需执行此操作$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.");
}