Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter and RestServer. How to upload images?

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!

like image 465
Jonathan Clark Avatar asked Aug 16 '11 11:08

Jonathan Clark


3 Answers

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';        
             }
like image 64
ssaltman Avatar answered Oct 20 '22 03:10

ssaltman


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);
    }
}
like image 42
sekati Avatar answered Oct 20 '22 05:10

sekati


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";
    }
like image 32
Ameen Maheen Avatar answered Oct 20 '22 05:10

Ameen Maheen