错误无效的数据类型,必须是数组或\\ ArrayAccess实例

时间:2017-06-14 19:48:48

标签: angularjs rest cakephp

当我发送图像和文本数据时,遇到下一个问题,当我将数据从angular发送到cakephp 3并进行休息服务并且不知道如何解决时会发生这种情况:

Possibly unhandled rejection: {
    "data":{
      "message":"Invalid data type, must be an array or \\ArrayAccess instance.",
      "url":"/documents/add",
      "code":500,
     "file":"C:\\xampp\\htdocs\\frontend_dekma\\app\\vendor\\cakephp\\cakephp\\src\\Utility\\Hash.php",
      "line":51
    }, 
    "status":500,
    "config":{
      "method":"POST",
      "transformResponse":[null],
      "jsonpCallbackParam":"callback",
    "headers":{
      "Access-Control-Allow-Origin":"*",
      "Access-Control-Allow-Headers":
      "Accept, Authorization, Cache-Control, Content-Type, X-Requested-With, x-csrf-token",
      "Accept":"application/json",
    "Authorization":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImV4cCI6MTQ5NzYzNzczNX0.im1g6BeHhMAF-MA0jhzYsU15UAH6BS1tByIqbj2acAQ"},
    "url":"/app/documents/add",
    "data":{}
    },
    "statusText":"Internal Server Error"}

现在有角度我的服务发送此信息:

.service('fileUpload', ['$http', function ($http) {
            this.uploadFileToUrl = function(file, uploadUrl){
                var formData = new FormData();
                console.log(file);
                // here take the values
                formData.append('photo', file.photo);
                formData.append('descripcion', file.descripcion);
                //show values formData
                for (var key of formData.entries()) {
                    console.log(key[0] + ', ' + key[1]);
                }
                //post url uploadUrl = '/app/documents/add'
                $http.post(uploadUrl, formData, {
                    transformRequest: angular.identity,
                    headers: {
                        'Access-Control-Allow-Origin' : '*',
                        'Access-Control-Allow-Headers': 'Accept, Authorization, Cache-Control, Content-Type, X-Requested-With, x-csrf-token',
                        'Content-Type': undefined
                    }
                })
                .then(function(response){
                    console.log(response);
                });
            }
        }])

这是我后端的控制器:

   public function add()
    {
        $document = $this->Documents->newEntity();
        $data = ['result' => 'null', 'id' => 'null'];
        if ($this->request->is('post'))
        {
            $document = $this->Documents->patchEntity($document, $this->request->getData());
            if ($this->Documents->save($document))
            {
                $data = ['result' => 'success', 'id' => $document->id];
            } else {
                $data = ['result' => 'error'];
            }
        }
        $this->set(compact('data'));
        $this->set('_serialize', ['data']);
    }

我有什么不同但有助于我发现问题出在哪里

首先我尝试使用cakephp-upload。但最初以博客的例子不清楚它是如何工作的,所以在开始时我遇到了这个错误我也不明白。现在我以不同的方式对待,一切正常,直到我试图将数据存储在数据库中时,错误发生时,实际上在帖子的开头继续出现相同的错误,但现在我知道问题在哪里:

经过多次测试后,我对此部分进行了评论并正常工作,但显然不会在DataBase中存储任何内容。使用不同的代码。现在工作,但需要将数据存储在数据库中,并了解错误。

public function add()
{
    $document = $this->Documents->newEntity();
    $data = ['result' => $this->request->getData(), 'id' => 'null'];
    $file = $this->request->getData('photo');
    $file['name'] =  time() . '-' . str_replace(' ', '_', $file['name']); // timestamp files to prevent clobber
    if (move_uploaded_file($file['tmp_name'], WWW_ROOT . 'files/' . $file['name']))
    {
        //When comment this part dont have error 
        //but can't save in the data base my information
        //
        /* 
        $document->photo = $file['name'];
        $document->descripcion = $this->request->getData('descripcion');
        $document = $this->Documents->patchEntity($document, $this->request->getData());
        if ($this->Documents->save($document)) {
            $data = ['result' => 'success', 'id' => $document->id];
        }
        */

    }
    $this->set(compact('data'));
    $this->set('_serialize', ['data']);
}

1 个答案:

答案 0 :(得分:0)

在〜80行发生异常: /home/user/myapp/vendor/josegonzalez/cakephp-upload/src/Model/Behavior/UploadBehavior.php

public function beforeSave(Event $event, Entity $entity, ArrayObject $options)
{
    foreach ($this->config() as $field => $settings) {
        if (Hash::get((array)$entity->get($field), 'error') !== UPLOAD_ERR_OK) {
            HERE ---> if (Hash::get($settings, 'restoreValueOnFailure', true)) {

博客的教程适用于早期版本,如果蛋糕还是不行。 请查看此文档:http://cakephp-upload.readthedocs.io/en/latest/examples.html

在DocumentsTable.php中你应该有这样的东西:

$this->addBehavior('Josegonzalez/Upload.Upload', [
    'path' => [],
]);

'path'不应该是值,而是数组的键:'path'=> [],