Rectangle 27 11

File Uploading with CodeIgniter

It seems the problem is you send the form request to welcome/do_upload, and call the Welcome::do_upload() method in another one by $this->do_upload().

$_FILES
var_dump($data['upload_data']);
NULL
welcome/second_method
$this->do_upload();

Then change the form helper function (within the View) as follows1:

// Change the 'second_method' to your method name
echo form_open_multipart('welcome/second_method');

CodeIgniter has documented the Uploading process very well, by using the File Uploading library.

You could take a look at the sample code in the user guide; And also, in order to get a better understanding of the uploading configs, Check the Config items Explanation section at the end of the manual page.

Also there are couple of articles/samples about the file uploading in CodeIgniter, you might want to consider:

Just as a side-note: Make sure that you've loaded the url and form helper functions before using the CodeIgniter sample code:

// Load the helper files within the Controller
$this->load->helper('form');
$this->load->helper('url');
form_open_multipart()
<form method="post" action="controller/method" enctype="multipart/form-data" />

I stumbled on this Q&A from a Google search for another question. You may want to update your answer with the following link codeigniter.com/userguide3/libraries/ as the ellislab.com/codeigniter/user-guide/libraries/ library is out of date.

How to upload image in CodeIgniter? - Stack Overflow

codeigniter file-upload
Rectangle 27 2

*Assuming you already happen to have a MY_Form_Validation library that extends the built in CodeIgniter stuff.*

I added some functions to validate portions of the $_FILE upload based on this:

I just copied the functions, not the entire file. I don't need the custom run or execute methods. Just the validation methods. (I already have a customization that allows me to mix the form_validation config file AND the controller rules together.)

/**
* tests to see if a required file is uploaded
* 
* @param mixed $file
*/
function file_required($file)
{
    if($file['size']===0)
    {
        $this->CI->form_validation->set_message('file_required','Uploading a file for %s is required.');
        return FALSE;
    }
    return TRUE;
}


/**
* tests the file extension for valid file types
* 
* @param mixed $file
* @param mixed $type
*/
function file_allowed_type($file,$type)
{
    //is type of format a,b,c,d? -> convert to array
    $exts = explode(',',$type);   
    //is $type array? run self recursively
    if(count($exts)>1)
    {
        foreach($exts as $v)
        {
            $rc = $this->file_allowed_type($file,$v);
            if($rc===TRUE)
            {
                return TRUE;
            }
        }
    }

    //is type a group type? image, application, word_document, code, zip .... -> load proper array
    $ext_groups = array();
    $ext_groups['image'] = array('jpg','jpeg','gif','png');
    $ext_groups['application'] = array('exe','dll','so','cgi');
    $ext_groups['php_code'] = array('php','php4','php5','inc','phtml');
    $ext_groups['word_document'] = array('rtf','doc','docx');
    $ext_groups['compressed'] = array('zip','gzip','tar','gz');
    $ext_groups['pdf'] = array('pdf');

    if(array_key_exists($exts[0],$ext_groups))
    {
        $exts = $ext_groups[$exts[0]];
    }

    //get file ext
    $file_ext = strtolower(strrchr($file['name'],'.'));
    $file_ext = substr($file_ext,1);

    if(!in_array($file_ext,$exts))
    {
        $this->CI->form_validation->set_message('file_allowed_type',"%s should be $type.");
        return false;        
    }
    else
    {
        return TRUE;
    }
}

I added the rules I wanted to my form_validation.php config file, but I treat my FILE input as if were included in the $_POST. Of course it isn't, but I will fix that in a moment. DON'T use the other types of validations built into CodeIgniter, only use your FILE validations!

$config = array(

            'form/index' => array(
                array( 'field'=>'my_upload_file', 'label'=>'File To Upload', 'rules'=>'file_required|file_allowed_type[pdf]'),
                ...

In my controller, add the $_FILE['my_upload_file'] to the $_POST array

if ( isset($_FILES['my_upload_file']) )
{
     $_POST['my_upload_file'] = $_FILES['my_upload_file'];
}

I think the big caveat is if you use the $_POST to populate your models or other actions. My code projects specifically grabs elements out of input->post() and I don't use mass assignment for much of anything. If you do use mass assignment, I would assume you messed up your assumptions.

Codeigniter FILE upload validation failure - Stack Overflow

validation file forms codeigniter upload
Rectangle 27 1

This is for Codeigniter version 2.2. If this question is still relevant. I traced the fault in file system/libraries/upload.php file to function: protected function _file_mime_type($file) at line 1032 and line 1046: $this->file_type = $matches[1]; When I was uploading a file with extension .txt the statement at line 1046 seems to assign an incorrect value of 'text/x-asm' to $this->file_type which is later compared to 'text/plain' and since mime types do not match the test fails and signals an inappropriate file type and error message:

'The filetype you are attempting to upload is not allowed'

Solution, not sure, but quick fix that appears to work, change condition of line 1032 to NOT so that it reads: if (!function_exists('finfo_file')) instead of: if (function_exists('finfo_file')). Hope this can help someone.

php - Uploading in Codeigniter - The filetype you are attempting to up...

php codeigniter
Rectangle 27 8

I ran into this problem aswell. The $_FILES data is sent a diffent structure (due to the multiple="" attribute) so codeigniter can't handle it. Prepend this before the uploading process:

$arr_files  =   @$_FILES['userfile'];

$_FILES     =   array();
foreach(array_keys($arr_files['name']) as $h)
$_FILES["file_{$h}"]    =   array(  'name'      =>  $arr_files['name'][$h],
                                    'type'      =>  $arr_files['type'][$h],
                                    'tmp_name'  =>  $arr_files['tmp_name'][$h],
                                    'error'     =>  $arr_files['error'][$h],
                                    'size'      =>  $arr_files['size'][$h]);

Then in the loop function use this:

$this->load->library('upload');

$arr_config =   array(  'allowed_types' =>  'gif|jpg|png',
                            'upload_path'   =>  'url_path/');

foreach(array_keys($_FILES) as $h) {

    // Initiate config on upload library etc.

    $this->upload->initialize($arr_config);

    if ($this->upload->do_upload($h)) {

        $arr_file_data  =   $this->upload->data();

    }

}

Explanation: I simply change the structure of $_FILES to the common structure which is sent on a default <input type="file" /> and the run a loop, fetching all their key names.

how can i get a var_dump() on the uploaded data before i proceed

You want information about the $_FILES data or the data which is created upon uploading with Codeigniter?

problem about the data has been solved. now i just want to the loop i should use to extract the info from the array.(provided in the update)

I can't tell exactly what you're after. I've updated the last code to hopefully make it clearer. You still need to change the structure of your $_FILES array before uploading this.

php - Codeigniter & HTML5 - Trying to Upload Multiple Images at Once -...

php codeigniter file-upload codeigniter-2
Rectangle 27 1

Codeigniter provides a library for uploading data. see File Upload Library and Image Library

This is the code I use for uploading images, creating a thumbnail + resizing the image

/*
* This function returns the path of imagemagick on your system
*/
public static function getLibPath()
{
    if(strlen(self::$_lib_path)==0)
    {
        self::$_lib_path=exec("/bin/bash -lc '/usr/bin/which convert'",$out,$rcode);
    }
    return self::$_lib_path;
}

/*
* This function handles the upload and calls the resizeImage function
* to generate the thumbnail and the resized image
*/
public function update()
{
    $config['upload_path'] = 'your upload path';
    $config['allowed_types'] = 'jpg|png|bmp';
    $config['max_size'] = '8192';//8mb //4096kb - 4mb
    $config['max_width']    = '0';
    $config['max_height']  = '0';
    $config['overwrite'] = false;
    $config['encrypt_name']=true;//this generates a filename for you

    $this->load->library('upload', $config);
    $result = $this->upload->do_upload();


    if($result) {
        $fileInfo=$this->upload->data();

        $this->resizeImage($fileInfo['full_path']);
        $data = array(
            'filename' => $fileInfo['file_name'],
            'orig_file_name' =>$fileInfo['orig_name'],
        );
        //pseudo function for storing the file info
        save_metadata_to_db($data);

    }
    else
    {
        echo $this->upload->display_errors());
    }
}
/*
* This function creates a thumbnail + the resized image
*/
private function resizeImage($filename)
{
   //This function creates a file with the orig. filename + _thumb

    $config['image_library'] = 'ImageMagick';
    $config['source_image'] = $filename;
    $config['create_thumb'] = TRUE;
    $config['maintain_ratio'] = FALSE;
    $config['width']    = 60;
    $config['height']   = 60;
    $config['library_path'] = $this->getLibPath();
    $config['quality'] = '100%';


    $this->load->library('image_lib', $config);

    if ( ! $this->image_lib->resize())
    {
       echo $this->image_lib->display_errors());
    }


    $config['create_thumb'] = False;
    $config['maintain_ratio'] = TRUE;
    $config['width']    = 1080;
    $config['height']   = 1920;

    $this->image_lib->initialize($config);

    if ( ! $this->image_lib->resize())
    {
        echo $this->image_lib->display_errors());
    }
}

php - Not able to create a thumbnail(resize) a profile image in Codeig...

php codeigniter codeigniter-3
Rectangle 27 4

Please, go through the following Description and the hint and get the Answer easily!

Actually as many ones have advised to add/replace the following line in the file (application/config/mimes.php):

But I have realized that in CodeIgniter Version 2.2.* the issue is little bit different! They have added that line already, but forgot to add the following "file_type" ==> 'application/vnd.ms-excel'

So adding the above 'application/vnd.ms-excel' into the array of xlsx file type, let me upload the .xlsx files!

Whenever you get the following error, on CodeIgniter Platform, and uploading files:

The filetype you are attempting to upload is not allowed.

Do the following in your Controller's upload method,

var_dump($this->upload->data());

And it will give you a huge array which you can get an idea from this link.(Please, see the end of that page). In that array you can get what's the real mime_type of the file you are trying to upload but not giving you to upload.

In my case, my file extension was, .xlsx , and the mime type was application/vnd.ms-excel , which was not added into the

'xlsx'  =>  array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip'),

So I added it manually, and after that it works VERRY WELL!!!

Same thing happened to uploading CSV once again, when I checked the file extension is .csv but the mime type was text/plain, when I added it to the following line:

and saved as follows,

'csv'   =>  array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain'),

It works like a charm! :D Try it, if you find something new within the above steps, please comment here!!! So, hoping this will be helpful to all of the CodeIgniter community, I posted it taking some time!

this is the best solution.Don't know why it hasn't got many upvotes.Thanks man

php - Upload xls or xlsx files with codeigniter, mime-type error - Sta...

php codeigniter upload mime-types
Rectangle 27 1

One of the issues is that file uploading uses a different mechanism than the other form <input> types. That is why $this->input->post("userfile") isn't getting the job done for you. Other answers have suggested using javascript's FormData and this one does too.

A very simple form for picking a file and submitting it. Note the change from a simple button to <input type="submit".... Doing so makes it a lot easier for the javascript to use the FormData object.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <script src="https://code.jquery.com/jquery-2.2.2.js"></script>
        <title>Upload Test</title>
    </head>
    <body>

        <?= form_open_multipart("upload/post", ['id' => 'uploader']); ?>
        <input type="file" name="userfile">
        <p>
            <input type="submit" value="Upload">
        </p>
        <?php echo form_close() ?>

        <div id="message"></div>

        <script>
            $('#uploader').submit(function (event) {
                event.preventDefault();
                $.ajax({
                    url: window.location.href + '/post',
                    type: "POST",
                    dataType: 'json',
                    data: new FormData(this),
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        console.log(data);
                        if (data.result === true) {
                            $("#message").html("<p>File Upload Succeeded</p>");
                        } else {
                            $("#message").html("<p>File Upload Failed!</p>");
                        }
                        $("#message").append(data.message);
                    }
                });
            });
        </script>
    </body>
</html>

Use FormData to capture the fields. Note that instead of handling the button click we handle the submit event.

$('#uploader').submit(function (event) {
    event.preventDefault();
    $.ajax({
        url: window.location.href + '/post',
        type: "POST",
        dataType: 'json',
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data) {
            //uncomment the next line to log the returned data in the javascript console
            // console.log(data);
            if (data.result === true) {
                $("#message").html("<p>File Upload Succeeded</p>");
            } else {
                $("#message").html("<p>File Upload Failed!</p>");
            }
            $("#message").append(data.message);
        }
    });
});

I've added some code that "reports" results to ajax and will display it on the upload page.

class Upload extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(['form', 'url']);
    }

    public function index()
    {
        $this->load->view('upload_v');
    }

    public function post()
    {
        $this->load->library("upload");
        $this->upload->initialize(array(
                "upload_path" => './uploads/',
                'allowed_types' => 'gif|jpg|png|doc|txt',
                "overwrite" => FALSE,
                "max_filename" => 300,
                "encrypt_name" => TRUE,
        ));

        $successful = $this->upload->do_upload('userfile');

        if($successful)
        {
            $data = $this->upload->data();
            $image_file = $data['file_name'];
            $msg = "<p>File: {$image_file}</p>";
            $this->data_models->update($this->data->INFO, array("image" => $image_file));
        } else {
            $msg = $this->upload->display_errors();
        }

        echo json_encode(['result' => $successful, 'message' => $msg]);
    }

}

This will upload your file. Your work probably isn't done because I suspect that your are not saving all the file info you need to the db. That, and I suspect you are going to be surprised by the name of the uploaded file.

I suggest you study up on how PHP handles file uploads and examine some of the similar codeigniter related questions on file uploads here on SO.

I don't know why but not working..

Forgot to mention this in the answer but I had to change the upload directory name from upload to uploads. Maybe you missed that? Other than data_models->update() which is a model I don't have the answer code worked for me. When you say, "not working." what exactly do you mean?

Thanks now working. The problem is in my php but i fixed it :)

success: function (data) {                 	console.log(data); }

But the file uploads OK?

javascript - Ajax upload not working codeigniter - Stack Overflow

javascript php jquery ajax codeigniter
Rectangle 27 1

Hope the html code in your form would be like this :

<form method="post" action="">
    <div class="form_label">
        <label for="form_field_name">Select : </label>
        <input type="file" name="form_field_name" />
    </div>
    <div class="message"><?php echo (isset($message['error'])) ? '<div class="error">' . $message['error'] . '</div>' : (isset($message['success']) ? '<div class="success">' . $message['success'] . '</div>' : ''); ?>
</form>
<?php
class My_upload extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
    }

    function upload_me()
    {
        $data['message'] = array();
        if(isset($_POST['submit'])) {
            $this->load->model('my_upload_model', 'umodel');
            $data['message'] = $this->umodel->upload_me();
        }
        $this->load->view('file_upload');
    }
}
?>

No file validation on controller, let us do it in model :

<?php
class My_upload_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    function upload_me()
    {
        // file upload configuration start //
        $config['file_upload_path'] = FCPATH . 'my_file_directory' . DIRECTORY_SEPARATOR . 'sub_directory' . DIRECTORY_SEPARATOR;
        $config['allowed_extensions'] = 'gif|jpg|jpeg|png|bmp';

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('form_field_name')) {
            return array('error' => $this->upload->display_errors());
        } else {
            return array('success' => 'File is uploaded successfully.');
        }
        // end file uploading //
    }
}
?>

Hope this will help you, let us know if anything there. please paste the code...

How make file field required in codeigniter - Stack Overflow

codeigniter
Rectangle 27 0

Uploading file in codeigniter is much easier. Here i am writting both code for view file and controller file.

<html>
<body>
<?php if(isset($error)){echo $error;} ?>
<?php if(isset($success)){echo $success;} ?>    
<?php echo form_open_multipart('upload_controller/do_upload');?>
<input type='file' name='userfile' size='20' />
<input type='submit' name='submit' value='upload' /> 
</form>
</body>
</html>
<?php 

class Upload_Controller extends CI_Controller {

public function __construct() {
     parent::__construct();
}

public function index(){
    $this->load->view('fileupload_view');
}

public function do_upload(){

if (!is_dir('/upload')) {
    mkdir('./upload',777,0);         
}

$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,    
);

$this->load->library('upload', $config);

if($this->upload->do_upload())
{
     $data['upload_data'] = $this->upload->data();
     $data['success']= 'File Successfully Uploaded';
     $this->load->view('fileupload_view',$data);
}
else
{
     $error = array('error' => $this->upload->display_errors());
     $this->load->view('fileupload_view', $error);
}
}
}
?>

php - File uploading error in Codeigniter - Stack Overflow

php codeigniter codeigniter-2 codeigniter-3
Rectangle 27 0

'xls' => array('application/excel', 'application/vnd.ms-excel', 'application/octet-stream'),

'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'application/x-zip', 'application/vnd.ms-excel', 'application/msword'),
'xls' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'application/x-zip', 'application/vnd.ms-excel', 'applica
    tion/msword'),

repalce with your previous mime type of xls and xlsx put the above code it can be work

xls two add not a problem

'xls' => array('application/excel', 'application/vnd.ms-excel', 'application/octet-stream'), working in to the my local but not working this live sit(Production site)

'xls' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'application/x-zip', 'application/vnd.ms-excel', 'applica
        tion/msword'),

it is working on the live production site

php - CodeIgniter: Excel file upload Error - Stack Overflow

php codeigniter file-upload
Rectangle 27 0

Codeigniter 2.1.4 has a bug as described here. So I've update CI to version 2.2.1, folowing the update instrucions here and here.

After checking the mimes.php file for a second time, I noticed a difference between my original file, and the one included in the newer version. I replaced the old one with the newer one, and the problem was solved.

Not documented in the upgrade instructions, is the fact that there is a difference between both files. The older (CI 2.1.4) of the file returns an array. The newer one (CI 2.2.1) does not return an array, but sets an array with the variable name $mimes.

php - Getting "filetype not allowed" with Codeigniter upload - Stack O...

php codeigniter file-upload upload mime-types
Rectangle 27 0

What I have found out on uploading through ajax in CodeIgniter is that when we submit the form the images doesn't get uploaded. Because of this I used an extra js file "jquery.form.min.js" and the ajax upload went well. To implement it the script would look like:

$('#uploadimg').ajaxForm({
       //uploadimg is my form id            
        dataType: 'json',
        success: processJson
});
function processJson(data) {
        if(data.msg=="success"){
             alert('Upload is successful.');
        }
        else{
             alert('Upload couldn't be completed.');
        }
}

The form would be

<form action="<?=base_url();?>controller/uploadImage/" method="post" enctype="multipart/form-data" id="uploadimg">

On submition this will call the uploadImg function in the controller and here saving the image and insertion in the database is done.

public function uploadImage(){
    //$id = $this->session->userdata('uid');
    $config[ 'upload_path' ]   = UPLOAD_DIR.'/newsletter/0';
    $config[ 'allowed_types' ] = 'gif|jpg|png';
    $config[ 'max_size' ]      = '1500';
    $config[ 'max_width' ]     = '1000';
    $config[ 'max_height' ]    = '1500';
    $image_name                = "files";
    $this->load->library( 'upload', $config );
    if ( $this->upload->do_upload( $image_name ) ) {
            $upload_data = $this->upload->data();
            if(!empty($upload_data)){
                $arg = array(
                            'name' => $upload_data[ 'file_name' ]
                );
                $this->modelName->insert($arg );
                $data['msg']="success";
            }
            else{
                $data['errmsg']="Couldnot upload the file!";
            }
    }
    else{
        $data['errmsg'] =$this->upload->display_errors();
    }
    echo json_encode($data);
}

Now this will trigger the processJson function in the script. And the upload shows the result.

You can find the javascript file on jquery.form.js.

wupendra I have a table where image is included. then I have a form incuding image as well, so i need to edit my function in my ajax and controller file where i can save an Image file to the database that the user uploaded.

I can upload image but nothing saves to the database

does the folder contains the uploaded image?

You haven't called the library function on your controller. If you follow the steps above it would work.

javascript - uploading image in a form using codeigniter/ajax - Stack ...

javascript php ajax codeigniter