首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用FormData和2检查数组是否为空

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

Stack Overflow用户
提问于 2018-03-04 23:16:03
回答 1查看 144关注 0票数 1

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

模型-

代码语言:javascript
复制
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.");
        }
    }
}

传递的数组如下:

代码语言:javascript
复制
name: "boned.jpg", type: "image/jpeg", tmp_name: "C:\xampp\tmp\php3684.tmp", error: 0, size: 25388

如您所见,数组不是空的,但是模型中的代码没有创建目录和上传文件。我检查了错误日志,它没有提到创建目录或上传文件,所以我不确定发生了什么。

哦,我在jquery调用中使用了FormData,所以以防万一,这是它的代码

代码语言:javascript
复制
$('#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;
    }
});

任何帮助都会很感激,因为这让我发疯了。

谢谢!

更新:

对不起,我以为我输入了控制器代码,这里又是:

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-06 10:48:35

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

代码语言:javascript
复制
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.");
        }
    }
}

尝试将代码更改为此,您将确切地知道问题发生在哪里。在我看来,您没有创建目录的权限。

代码语言:javascript
复制
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.");
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49101542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档