Admin area - Upload photo api

Update at 2017-12-22 07:58:30


Image is a common form of information in web applications. CI Base provides an API that allows you to upload images and store them on your website


To upload the image, send a POST method request to the /admin.php/photo/upload path, where the data is input from an input file named photo.

You can refer to the following form

<form action="/admin.php/photo/upload" enctype="multipart/form-data">
    <?php echo $csrf_token ?>
    <input type="file" name="photo" accept="image/*" />
    <button type="submit">Upload</button>

If the upload succeeds, the result will return the json according to the structure

    "success": true,
    "message": "Uploaded",
    "path": "path/to/your/photo/after/upload",
    "cache": "path/to/your/photo/cached/after/upload"

The opposite will return the json error as follows

    "success": false,
    "message": "Upload fail",
    "errors": [
        "error_1": "Error 1",
        "error_1": "Error 1"

Use ajax to upload

By returning a json after the request, you can easily use ajax to upload the image, instead of using it as a regular html. And you should also apply this to your app

An example of using ajax in jquery in combination with api upload images is the following

<form action="<?php echo url('api/photo/upload') ?>" method="post" enctype="multipart/form-data" id="form-upload">
    <?php echo $csrf_token ?>
    <input type="file" id="input-file" name="photo" accept="image/*" />
<script type="text/javascript">
    $(function () {
        $('#input-file').change(function () {
            var $form = $('#form-upload')
            var formData = new FormData($form[0]);
                url: $form.attr('action'),
                type: $form.attr('method'),
                dataType: 'json',
                data: formData,
                processData: false,  
                contentType: false,
                success : function(json) {
                    alert('open console to view result');