Yii Rest Service Image Upload

I’ve recently got up to speed on creating a Yii REST web service that posts a record to the database using a Model and API Controller. I’m confused, though, on how to handle an image upload. I’d like to upload an image and post a record to a db table all in one REST service request. I think I need to use a POST method with a Content-Type of “multipart/form-data”. Is that correct? Is it possible to post the image and db record data all in once REST service post? Are there any code examples anywhere for me to refer to? I’ve googled for days without any luck. Also, I’d like to be able to test the service with the Firefox RESTClient plugin. I’m confused on what the Request Body would look like when the content type is multipart/form-data. Thanks.

Aaron

I just had to do this for a client. We ended up encoding the image as base64 and sending it in the POST body. When the API receives the request, grab the encoded string, decode it, and save it to disk.

My example parses some XML but you should get the basic idea.




public function actionCreate()

{

    try

    {

        $xml = new SimpleXMLElement(file_get_contents("php://input"));


        $decodedImage = base64_decode($xml->headshot);


        file_put_contents("full/path/to/new/image.jpg", $decodedImage);

    }

    catch (Exception $exception)

    {

        echo $exception->getMessage();

    }

}



Matt

It is possible to post some data along with file using POST with “multipart/form-data” encoding. On the REST server side it will look like usual PHP form upload - data will be available in $_POST and files in $_FILES (or through Yii’s CUploadedFile).

On the client side such encoding should be supported. But usually REST/HTTP client libraries already support this, for example, I used Zend REST client and node.js superagent.

As for testing - I did not used Firefox RESTClient, but usually you need to set "application/x-www-form-urlencoded" header, in the request body should go your data, like "model[field1]=x&model[field2]=y" and extension should support file attachments.

What does this for me is "RESTConsole" extension for Chrome.

It’s basically the same kind of extension, but for Chrome. :)

[color="#006400"]/* Moved from General Discussion to Tips, Snippets and Tutorials … */[/color]

You should check http://www.yiiframework.com/extension/xupload as it does exactly that: sends data (image + additional data) through an AJAX call using multipart/form-data.