cakephp web services how to write an action that allows me to upload a file
cakephp, file-upload, json, rest, web-services
Solution
I figured it out after sometime.
Assuming the following setup
- Cakephp 2.x
- the action here is public for anonymous users
Step 1. Install Webservice Plugin by josegonzalez.
Step 1.1. Setup Router::parseExtensions for json
Step 1.2. Add 'Webservice.Webservice' to the components of PostController
Step 1.3. Load the Plugin
Step 2. You need to change the following action for 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'));
}
}
Step 3. Setup your Flex code as stated in this answer here. This is how you then retrieve the JSON response in Flex Actionscript.
Step 4. You should expect to get back a json response consisting of the 3 variables result, error, and id and the cake validationErrors. You may choose to blacklist validationErrors as stated in the plugin.
Problem
I am using cakephp 2.1.0 I have a Post Controller that basically creates a Post that has id as integer, title, image as string I have a controller action that can work with a view that allows me to upload a file and create a new Post record. The action is called admin_add This is working. However, I want to expose this action admin_add such that a desktop app built in Adobe Flex can call it. Preferably I want to use RESTful actions. Basically I want to create this action as a web service. Most tutorials I see online tend to be for READ-only actions such as view and index. What changes do I need to add to the cakephp application code?