Codeigniter and RestServer. How to upload images?

18,228

Solution 1

Ok,

There is another solution here: FIle upload from a rest client to a rest server

But neither of these solutions worked for me.

However, this is what worked; actually worked.

First, I wasn't sure if my file was reaching the method, so I changed the response line to:

function enter_post()
    {

        $this->response($_FILES);
    }

Note, this is a great way to test your REST methods.

You can also output:

$this->response($_SERVER);

and

$this->response($_POST);

etc.

I got the following JSON output:

{"file":{"name":"camel.jpg","type":"application/octet-stream","tmp_name":"/tmp/phpVy8ple","error":0,"size":102838}}

So I knew my file was there.

I then changed the method to find and move the file. I used common file access script to get the file from its temp location and move it to a new location:

    $uploaddir = '/home/me/public_html/uploads/';

    $uploadfile = $uploaddir . basename($_FILES['file']['name']);

    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
        $data['status'] = 'uploaded';       
            } else {
        $data['status'] =  'failed';        
             }

Solution 2

You can actually use CodeIgniter's native File Upload Class to facilitate uploads with Phil's Rest-Server like this:

/**
 * REST API Upload using native CI Upload class.
 * @param userfile - multipart/form-data file
 * @param submit - must be non-null value.
 * @return upload data array || error string
 */
function upload_post(){
    if( ! $this->post('submit')) {
        $this->response(NULL, 400);
    }
    $this->load->library('upload');

    if ( ! $this->upload->do_upload() ) {
        $this->response(array('error' => strip_tags($this->upload->display_errors())), 404);
    } else {
        $upload = $this->upload->data();
        $this->response($upload, 200);
    }
}

Solution 3

try this code ,image is saved with time stamp and its extension ..

$uploaddir = 'uploads/';
    $path = $_FILES['image_param']['name'];
    $ext = pathinfo($path, PATHINFO_EXTENSION);
    $user_img = time() . rand() . '.' . $ext;
    $uploadfile = $uploaddir . $user_img;
    if ($_FILES["image_param"]["name"]) {
        if (move_uploaded_file($_FILES["image_param"]["tmp_name"],$uploadfile)) {
echo "success";
    }
Share:
18,228
Jonathan Clark
Author by

Jonathan Clark

I am a single man working in a computer store here in New York. Trying to learn how to code in Python. Soon getting there.

Updated on July 29, 2022

Comments

  • Jonathan Clark
    Jonathan Clark almost 2 years

    I am coding an API using Phils RestServer (see link) in Codeigniter. I need a way to upload images via the API. How can I do that? Is it just as simple as making a POST request with the correct headers (what headers to use)?

    https://github.com/philsturgeon/codeigniter-restserver

    Thankful for all input!