json - cakephp Web服务如何编写允许我上传文件的 Action

标签 json web-services cakephp rest file-upload

我正在使用 cakephp 2.1.0

我有一个帖子 Controller ,它基本上创建一个帖子,其 id 为整数、标题、图像为字符串

我有一个 Controller 操作,它可以与允许我上传文件并创建新 Post 记录的 View 一起使用。该操作称为 admin_add

这是有效的。

但是,我想公开此操作 admin_add 以便内置于 Adob​​e Flex 的桌面应用程序可以调用它。

最好我想使用 RESTful Action 。

基本上我想将此操作创建为 Web 服务。

我在网上看到的大多数教程都倾向于只读操作,例如 View 和索引。

我需要向 cakephp 应用程序代码添加哪些更改?

最佳答案

一段时间后我想通了。
假设以下设置

  • Cakephp 2.x
  • 此处的操作对匿名用户是公开的

  • 步骤 1. 安装 Webservice Plugin约瑟冈萨雷斯
    步骤 1.1。为 json 设置 Router::parseExtensions
    步骤 1.2。将“Webservice.Webservice”添加到 PostController 的组件中
    步骤 1.3。加载插件

    步骤 2. 您需要为 PostController 更改以下操作
        public function add() { 
        
        if ($this->request->is('post')) {
    
            // create new Post -- this will grab the file from the request data
            $newPost = $this->Post->createNew($this->request->data);
        
            if ($newPost) {
                $this->Session->setFlash(__('Your Post has been saved'));
                // for normal webpage submission
                if (empty($this->request->params['ext'])) {
                    $this->redirect('/');                   
                } else {        
                    // for json response to Flex client 
                    $result = $newPost;
                    $error = null;
                    $id = null;
                }
            } else {
                $this->Session->setFlash(__('Your Post could not be saved. Please, try again.'));
                // for json response for failure to create
                if (!empty($this->request->params['ext'])) {
                
                        
                        $result = null;
                        $error = 'Your Post could not be saved.';
                        $id = null;
                
                }
                
            }
            // this is for json response via Webservice.Webservice
            $this->set(compact('result', 'error', 'id'));
            
        }
    
        }
    

    第 3 步。按照此答案 here 中的说明设置您的 Flex 代码.这是how you then retrieve the JSON response在 Flex ActionScript 中。

    第 4 步。您应该期望得到一个 json 响应,其中包含 3 个变量 result、error、id 和 cake validationErrors。您可以选择按照插件中的说明将validationErrors 列入黑名单。

    关于json - cakephp Web服务如何编写允许我上传文件的 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10749752/

    相关文章:

    c# - 如何通过 API 从维基百科获取地标性地点的标题?

    java - 两个隔离系统之间的同步

    CakePHP 寻找不存在的列

    java - 在 REST API 响应中返回登录凭据的最佳实践是什么?

    cakephp - 如何在 CakePHP 1.3 中更新 HABTM 关联模型?

    使用前缀路由时 url 中的 CakePHP3.x Controller 名称

    json - 编辑大型 JSON 文件

    c# - Json.Net 在使用我的 JsonConverter 之前自行转换

    java - 使用@DateTimeFormat保存json-dto时如何记住偏移量?

    c# - 如何使用 dotnet 使用 ColdFusion Web 服务