Step 1Create a uploads folder in root directory
Step 2Create the Attachment.php(Controller) file
Step 3Create the create_attachment.php(View) File
Step 4Create the AttachmentModel.php(Model) File
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Attachment extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('attachmentmodel');
}
public function CreateAttachment(){
$page_data['page_title'] = 'Create Attachment';
$page_data['page_name'] = "attachment/create_attachment";
$this->load->view('backend/index', $page_data);
}
public function ManageAttachment(){
extract($this->input->post());
$data['Title']=$Title;
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('file'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$filedata = $this->upload->data();
}
$data['Logo']=$filedata['file_name'];
$data['Path']=$filedata['file_path'];
$response=$this->attachmentmodel->ManageAttachment($data,1);
if($response){
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response));
}
}
}
<div class="form-group">
<label>Title <span class="required">*</span></label>
<input type="text" name="Title" id="Title" class="form-control" value="<?php echo $values->Title;?>">
</div>
<label class="form-label">Upload File <span class="required">*</span></label><br>
<input type="file" id="file" name="userfile" size="20" />
<script>
$(document).ready(function(){
jQuery(document).on('click','#submit',function(e) {
var file_data = $("#file").prop('files')[0];
var form_data = new FormData();
var Title=$("#Title").val();
var ext = $("#file").val().split('.').pop().toLowerCase();
if ($.inArray(ext, ['png','jpg','jpeg']) == -1) {
alert("only jpg and png images allowed");
return;
}
var picsize = (file_data.size);
if(picsize > 2097152) /* 2mb*/
{
alert("Image allowd less than 2 mb")
return;
}
form_data.append('file', file_data);
form_data.append('Title',Title);
$.ajax({
url: '<?php echo base_url()?>attachment/ManageAttachment', /*point to server-side PHP script */
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(res){
$(".alert_success").show();
$("#success_message").text("Attachment created successfully !");
window.location.hash = '#success_message';
window.location = `<?php echo base_url()?>attachment`;
}
});
});
})
</script>
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class AttachmentModel extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function ManageAttachment($data,$type,$id=""){
if($type==1){
$this->db->insert('attachmentmst',$data);
return $this->db->insert_id();
}
}
}