How to upload image in codeigniter using ajax with server validation - php

I have a form which data is inserting into data base through ajax. Along with when input fields has error then showing error under neath to the every fields.
But when i select the image and trying to upload the name of image into database, then nothing goes on, neither image uploading to the upload path nor inserting the name of the image into database.
In Case of image upload error i can not even display image upload error.
Controller:-
In my Controller as you can see that i have an array named result which has two keys status and message and default status is false.
In the else part a loop is running which has only form error not any type of image error may be this is reason for not showing any error for image.
No Problem if error is not showing But at least file name should be inserting.
function infoValidation() {
$result = array('status' => false, 'message' => array());
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run('company_registration')) {
$config['upload_path'] = 'assets/uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload',$config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$data['upload_data'] = $this->upload->data('file_name');
$image_name = $data['upload_data'];
//$result['message'] = $this->upload->display_errors();
//$result['status'] = false;
}
else
{
$image_name = '';
}
$data = array(
'email' => $this->input->post('email'),
'first_name' => $this->input->post('firstname'),
'last_name' => $this->input->post('lastname'),
'pincode' => $this->input->post('pincode'),
'state' => $this->input->post('state'),
'landmark' => $this->input->post('landmark'),
'address' => $this->input->post('address'),
'state' => $this->input->post('state'),
'image' => $image_name,
'joined_date' => date('Y-m-d H:i:s')
);
$result['status'] = true;
$this->Perfect_mdl->c_insert($data);
}else {
foreach ($_POST as $key => $value) {
$result['message'][$key] = form_error($key);
}
}
echo json_encode($result);
}
Ajax:
$("#form").submit(function(e){
e.preventDefault();
var me = $(this);
$.ajax({
url : me.attr('action'),
dataType : 'json',
type : 'POST',
data : me.serialize(),
success: function(resp) {
console.log(resp);
if (resp.status == true) {
$('#myModal').modal('show');
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
}else {
$('#msg').html('<div class="alert alert-danger"><h5>Please Check Your Details</h5></div>');
$.each(resp.message, function(key, value) {
var element = $("#"+key);
element.closest('.form-group')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger').remove();
if(element.parent('.input-group').length) {
element.parent().after(value);
} else {
element.after(value);
}
// element.after(value);
});
}
}
});
});
How can i Upload an image into database, If this is not the right way then please Suggest the right way for doing this

serialize() method not able to post file data.
For sending file using ajax use FormData instead of serializing
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
View
<form action="Your controller method name" method="post" id="form_img" enctype="multipart/form-data" accept-charset="utf-8">
<div>
username : <input type="text" name="name">
<span class="error name"></span>
</div>
<div>
password : <input type="text" name="password">
<span class="error password"></span>
</div>
<div>
file : <input type="file" name="image">
<span class="error image"></span>
</div>
<input type="submit" name="submit" value="submit">
</form>
Jquery call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").attr('action'),
dataType : 'json',
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
$('.error').html('');
if(resp.status == false) {
$.each(resp.message,function(i,m){
$('.'+i).text(m);
});
}
}
});
});
});
</script>
controller
function test_image() {
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'name', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run() == TRUE) {
if($_FILES['image']['error'] != 0) {
$result['status'] = false;
$result['message'] = array("image"=>"Select image to upload");
} else {
$config['upload_path'] = 'images';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload',$config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$data['upload_data'] = $this->upload->data('file_name');
$image_name = $data['upload_data'];
}
else
{
$image_name = '';
}
$data = array(
'name' => $this->input->post('name'),
'password' => $this->input->post('password'),
'image' => $image_name,
'joined_date' => date('Y-m-d H:i:s')
);
$result['status'] = true;
$this->Perfect_mdl->c_insert($data);
$result['message'] = "Data inserted successfully.";
}
}else {
$result['status'] = false;
// $result['message'] = validation_errors();
$result['message'] = $this->form_validation->error_array();
}
echo json_encode($result);
}
Try this flow for upload image using ajax

Files cannot be uploaded with serialize() function, as it does not serialize files. Please try this approach:
var data = new FormData(this);
$.ajax({
url : me.attr('action'),
dataType : 'json',
contentType : false,
processData : false,
type : 'POST',
data : data,
success: function(resp) { ... etc.

try this codein view
$('#formElement').submit(function () {
var formData = new
FormData(document.getElementById("formElement"));
formData.append('image-file', $('#image-file')[0].files[0]);
$.ajax({
url: "<?php echo base_url('home/add')?>",
data: formData,
contentType: false,
processData: false,
type: 'POST',
beforeSend: function() {
$('.loder_img').show();
},
success: function ( data ) {
$('.loder_img').hide();
var val = JSON.parse(data);
//you can apply alerts or anything to show validation on
view and in val all mesg of validation yon can see here in console.
console.log(val);
},
error: function (request, status, error) {
$('.loder_img').hide();
alert(request.responseText);
}
});
});
and in your controller
public function addPackage()
{
$this->load->library("form_validation");
//left side form
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('txt_desc', 'Remarks', 'required|trim');
$this->form_validation->set_rules('txt_store', 'Store', 'required|trim');
//upto so on according to your values
if( $this->form_validation->run() == false){
$error = array(
"check_1" => form_error('check_1'),
"txt_desc" => form_error('txt_desc'),
"txt_store" => form_error('txt_store'),
"txt_couple_name" => form_error('txt_couple_name'),
"txt_couple_case" => form_error('txt_couple_case'),
"txt_phone" => form_error('txt_phone'),
"txt_date" => form_error('txt_date'),
"txt_location" => form_error('txt_location'),
"txt_address" => form_error('txt_address'),
"txt_email" => form_error('txt_email'),
);
$msg = array('status' => 'invalid', 'msg'
=>$error,'allerror'=>validation_errors());
echo json_encode($msg);
}else{
//insert it into database all file and values
if($_FILES["image-file"]["size"] != 0){
$path= './uploads/image';
$img = "image/".$this->Upload_model->image_upload($path, "", '', '', '',"image-file");
}
$data = array(
"basket" => $this->filter($this->input->post("check_1",true))........
);
//your insert query
}
}
and in your model to upload image and it will return the uploaded image if it is not upload hen it will return false or you can print the display errors and dont forget to change the path of storing image
model code
public function image_upload($upload_path, $max_width, $max_height, $min_width, $min_height, $filename)
{
$config['upload_path'] = $upload_path;
$config['file_name'] = date('Ymd_his_').rand(10,99).rand(10,99).rand(10,99);
$config['allowed_types'] = "gif|jpg|png|jpeg|JPG|JPEG|PNG|bmp";
$config['overwrite'] = FALSE;
$config['max_size'] = '0';
$config['max_width'] = $max_width;
$config['max_height'] = $max_height;
$config['min_width'] = $min_width;
$config['min_height'] = $min_height;
$config['max_filename'] = '0';
$config['remove_spaces'] = FALSE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($filename))
{
/*$data['upload_data']['file_name'] = '';
$msg = $this->upload->display_errors('');
$this->session->set_flashdata('msg',$msg);
$url = $_SERVER['HTTP_REFERER'];
redirect($url); */
return false;
//return $error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$config['source_image'] = $config['upload_path'].$data['upload_data']['file_name'];
$config['quality'] = '100%';
$this->load->library('image_lib', $config);
return $data['upload_data']['file_name'];
}
unset($config);
$this->image_lib->clear();
}

Jquery serialize() method not able to post file data.
Please used jquery plugin for post file data using ajax. which are given below.
dmuploader.js
dmuploader.min.js
for simple example click here

Related

Multiple images are not uploaded using jquery ajax in codeigniter

In my code I have an input field having name product_image where I want to upload and insert multiple files into my database like this img1.jpg,img2.jpg,img3.jpg. But Now, what happen when I select 4 files i.e. img1.jpg,img2.jpg,img3.jpg,img4.jpg only img4.jpg store in my database and only this file are moving in my folder.
view:
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
product_name = $("#product_name").val();
var formData = new FormData();
$.each($("#product_image"), function (i, obj) {
$.each(obj.files, function (j, file) {
formData.append('product_image[' + i + ']', file);
});
});
formData.append('product_name', product_name);
$.ajax({
type:"POST",
data:formData,
processData: false,
contentType: false,
url:"<?php echo base_url(); ?>admin/products",
success:function(data){
$("#success_upload").html(data);
}
});
});
});
</script>
<input type="text" class="form-control" id="product_name" name="product_name">
<input type="file" id="product_image" name="product_image[]" multiple>
<input type="submit" class="btn btn-primary" id="submit" name="submit">
Controller:
public function products()
{
$dataInfo = array();
$files = $_FILES;
$cpt = count($_FILES['product_image']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['product_image']['name']= $files['product_image']['name'][$i];
$_FILES['product_image']['type']= $files['product_image']['type'][$i];
$_FILES['product_image']['tmp_name']= $files['product_image']['tmp_name'][$i];
$_FILES['product_image']['error']= $files['product_image']['error'][$i];
$_FILES['product_image']['size']= $files['product_image']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload('product_image');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name'];
$fileName = $upload_data['file_name'];
$images[] = $fileName;
}
$fileName = $images;
$data = array(
'product_name' => $this->input->post('product_name'),
'product_image' => implode(",",$fileName),
);
$sql = $this->db->insert('add_product',$data);
if($sql == true)
{
echo '<p style="color:green;">New Product Added</p>';
}
else
{
echo '<p style="color:red;">Unable to Proceed!</p>';
}
}
private function set_upload_options()
{
$config = array();
$config['upload_path'] = FCPATH.'resource/product/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '1024';
$config['overwrite'] = FALSE;
return $config;
}
So, How can I upload and insert multiple files into my database? Please help me.
Thank You

When uploading image in codeigniter the image is not saved into the path folder

When I upload an image in Codeigniter its name is saved to the database but not in the default folder. I'am using Ajax to submit the image
My "view" profile
<div id="timelineBackground">
<?php
{
$image_properties = array('src' => base_url("uploads/" . $timeline_image),'width' => '1000px','height'=> '400px','id'=>'coverimg', 'title' => 'That was quite a night','rel' => 'lightbox');
//echo img($image_properties);
?>
<div id="timelineselector">
<?php echo form_open_multipart('',["id"=>"form_cover"]); ?>
<input type="hidden" name="email" value="<?php echo $email ;?>" >
<?php echo form_upload(["name"=>"timelineimage"]); ?>
<?php echo form_submit(["name"=>"submit","value"=>"Submit"]); ?>
<?php echo form_close(); ?>
</div><?php
}
?></div>
here is my ajax code
jQuery('#form_cover').submit(function(e){
e.preventDefault();
var formData = new FormData(this);
var url= '<?php echo base_url("user/coverimage"); ?>';
formData.value
jQuery.ajax({
type: "POST",
url:url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data)
{
$('#coverimg').attr('src',data);
},
error: function(data){
//error function
}
});
});
my controller "user"
public function coverimage(){
$config = [
'upload_path' => './uploads/',
'allowed_types' => 'jpg|gif|png|jpeg',
'max_size' => 10000000000000,
'max_width' => 1024000000,
'max_height' => 7680000000,
];
$this->load->library('upload', $config);
if(!$this->upload->do_upload('timelineimage') ) {
$post = $this->input->post();
unset($post['submit']);
$upload_data = $this->upload->data();
$file_name=$_FILES['timelineimage'];
$this->load->model('Pmodel');
$this->Pmodel->timeline_upload_model($post,$file_name);
$image_properties = array(
'src' => base_url("./uploads/" . $file_name['name']),
'width' => '200px',
'height'=> '200px',
'title' => 'That was quite a night',
'rel' => 'lightbox'
);
// echo img($image_properties);
echo base_url("uploads/" . $file_name['name']);
exit();
}else {
$upload_error = $this->upload->display_errors();
$this->load->view('admin/add_article',compact('upload_error'));
}
}
my model "Pmodel"
public function timeline_upload_model($arr,$arra)
{
$email=$arr['email'];
$image=$arra['name'];
$data=array('timelineimage'=>$image);
$query=$this->db->where('email',$email)->update('user_data',$data);
return $query;
}
Why does it only show the name but not the image?
I found the answer and posted the code, in case anyone else wants to look at this...
the 'view'
<div id="timelineBackground">
<?php
{
$image_properties = array('src' => base_url("uploads/" . $timeline_image),'width' => '1000px','height'=> '400px','id'=>'coverimg', 'title' => 'That was quite a night','rel' => 'lightbox');
echo img($image_properties);
?>
<div id="timelineselector">
<?php echo form_open_multipart('user/coverimage',["id"=>"form_cover"]); ?>
<input type="hidden" name="id" value="<?php echo $id ;?>" >
<?php echo form_upload(["name"=>"timelineimage"]); ?>
<?php echo form_submit(["name"=>"submit","value"=>"Submit"]); ?>
<?php echo form_close(); ?>
</div><?php
}
?></div>
'ajax'
jQuery('#form_cover').submit(function(e){
e.preventDefault();
var formData = new FormData(this);
var url= '<?php echo base_url("user/coverimage"); ?>';
formData.value
jQuery.ajax({
type: "POST",
url:url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data)
{
$('#coverimg').attr('src',data);
},
error: function(data){
//error function
}
});
});
and the controller:
public function coverimage()
{
print_r($_POST);
print_r($_FILES);
$config = [
'upload_path' => './uploads/',
'allowed_types' => 'jpg|gif|png|jpeg',
'max_size' => 10000000000000,
'max_width' => 1024000000,
'max_height' => 7680000000,
];
$this->load->library('upload', $config);
$this->upload->initialize($config);
$timelineimage="timelineimage";
if(!$this->upload->do_upload($timelineimage))
{
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/profile',compact('upload_error'));
}
else
{
$post = $this->input->post();
unset($post['submit']);
//print_r($post);
$upload_data = $this->upload->data();
//print_r($upload_data);
$file_name=$_FILES['timelineimage'];
$this->load->model('Pmodel');
$this->Pmodel->timeline_upload_model($post,$file_name);
$image_path= base_url("uploads/".$upload_data['raw_name'].$upload_data['file_ext']);
//echo base_url("uploads/" . $file_name['name']);
}
}

CakePHP - Load view with php variables and return in ajax

Ok, this has been driving me crazy for the past couple of days.
I have a form:
echo $this->Form->create(FALSE, array('id' => 'AdminGeneralReport', 'class' => 'ReportForm'));
echo '<div class="row">';
echo $this->Form->input('ReportCenter', array(
'type'=>'select', 'div' => 'form-group',
'options' => $centers,
'label' => 'المركز',
'class' => 'form-control report-center',
'selected' => isset($selections['CenterID'])? $selections['CenterID']['value'] : 'default'
));
echo $this->Form->input('ReportYears', array(
'type'=>'select', 'div' => 'form-group',
'options' => $years,
'label' => 'العام الدراسي',
'class' => 'form-control report-year',
'selected' => isset($selections['YearID'])? $selections['YearID']['value'] : 'default'
));
echo $this->Form->end();
Submit jQuery:
$('.ReportForm').off('submit').on('submit', function(e){
e.preventDefault();
var formID = $(this).attr('id');
var data = JSON.stringify($(this).serializeObject());
var url = base_url + "Reports/" + formID;
var targetSelector = $(this).attr('data-target') || '.results-row';
var $target = $(targetSelector);
// Show app loading
$('#AppLoading').show();
$.ajax({
url : url,
type : 'POST',
ContentType : 'application/json',
data : {'data': data}
}).done(function(response){
try{
response = JSON.parse($response);
if(response.status == 'success'){
$target.html(response.html);
}
else{
$('#AppWell').show('slow').children('p').html(response.msg);
}
}
catch (ex) {
var msg = 'عذراً، حدث خطأ في إنشاء التقرير. برجاء المحاولة لاحقاً';
$('#AppWell').show('slow').children('p').html(msg);
console.log('Exception :: ' + ex.toString());
console.log('Response :: ' + response);
}
}).fail(function(request, status, error){
var msg = 'عذراً، حدث خطأ في إنشاء التقرير. برجاء المحاولة لاحقاً';
$('#AppWell').show('slow').children('p').html(msg);
console.log('XXXXX Ajax Failure :: ' + error);
}).always(function(){
// Hide app loading
$('#AppLoading').hide();
});
});
Question/Need: I want to load another view and append it after this form using json or whatever the way it's possible.
This is part of the view I want to load:
<?php if(isset($selections['Filtered']) && $selections['Filtered'] == TRUE ){
echo '<div class="row">';
$Report = '';
if(isset($selections['SexID']) && $selections['SexID']['value'] != 'default'){
$Report .= '<div class="report-info">
<p class="title">الجنس</p>
<p class="value">'.$selections['SexID']['text'].'</p>
</div>';
}
if(isset($selections['GovID']) && $selections['GovID']['value'] != 'default'){
$Report .= '<div class="report-info">
<p class="title">المحافظة</p>
<p class="value">'.$selections['GovID']['text'].'</p>
</div>';
}
echo '</div>';
?>
<div class="cur-report custom-inverse">
<?=$Report;?>
</div>
And this is part of the PHP code:
// This is the function the ajax calls
public function AdminGeneralReport()
{
// Enable automatic view class switching on content types
public $components = array('RequestHandler');
// Disable auto rendering
$this->autoRender = false;
// Create new view to return to ajax request
$view = new View($this, false);
// Define selections array
$selections = array();
// Get AJAX data
$postData = $this->request->data;
// Decode post data to JSON object
$data = json_decode($postData);
// Create response object
$response = new stdClass();
$response->status = 'fail'; // Should be changed by success scenario
// ********* Center Condition ********* //
$centerCond = '';
// Check if Center is set
if($data->ReportCenter != 'default'){
$centerID = $data->ReportCenter;
$selections['CenterID']['value'] = $centerID;
$selections['CenterID']['text'] = $centers[$centerID];
$selections['Filtered'] = TRUE;
$centerCond = array('CenterID' => $centerID);
}
// *********************************************** //
// ********* Year Condition ********* //
$yearCond = '';
// Check if Academic Year is set
if($data->ReportYears != 'default'){
$yearID = $data->ReportYears;
$selections['YearID']['value'] = $yearID;
$selections['YearID']['text'] = $years[$yearID];
$selections['Filtered'] = TRUE;
$yearCond = array('YearID' => $yearID);
$allTerms = $this->Term->find('all', array('conditions' => array('YearID' => $yearID),
'fields' => array('ID', 'TermName')));
// Convert results from 3D array to 1D array
for($i = 0; $i < count($allTerms); $i++){
$terms[$allTerms[$i]['Term']['ID']] = $allTerms[$i]['Term']['TermName'];
}
$terms['default'] = 'الكل';
}
// *********************************************** //
if($selections){
$response->status = 'success';
}
else{
$response->msg = 'لا توجد بيانات لهذه الإختيارات';
}
$view->set(compact('results','selections'));
$view->set('_serialize', array('results', 'selections'));
$html = $view->render('Admin/General', FALSE);
$response->html = $html;
echo json_encode($response);
die();
}
NOTE: I have this configured in Config/router.php
/**
* Enable extensions routing for data views
*/
Router::parseExtensions('json');
FINALLY SOLVED!!!
I was confusing my self by trying to make it a data view json/xml... while all i needed to do was formatting the returned view:
The returned view has a lot of "\r\n\'\""...all the escape sequences that fail to be JSON parsed in jQuery code.
and i don't have to include the Router::parseExtensions('json'); as well as the public $components = array('RequestHandler');
So this is the PHP Code:
$results = array(); // Fill it
$selections = array(); // Fill it
...
// Disable auto rendering
$this->autoRender = false;
// Create new view to return to ajax request
$view = new View($this, false);
$view->set(compact('results','selections'));
$view->set('_serialize', array('results', 'selections'));
$html = stripcslashes( stripslashes( $view->render('Admin/General', FALSE) ) );
$response->html = $html;
echo json_encode($response);
die();
NOTE: stripcslashes() removes the "\r\n" escape sequences, while stripslashes will remove "\'\"" escape sequences
The jQuery Code:
$.ajax({
url : url,
type : 'POST',
ContentType : 'application/json',
data : {'data': data}
}).done(function(response){
try{
response = JSON.parse(response);
if(response.status == 'success'){
$target.html(response.html);
}
else{
// ERROR HANDLING
}
}
catch (ex) {
// ERROR HANDLING
console.log('Exception :: ' + ex.toString());
console.log('Response :: ' + response);
}
}).fail(function(request, status, error){
// ERROR HANDLING
console.log('XXXXX Ajax Failure :: ' + error);
}).always(function(){
// Hide loading
});

PHP is not recieving JSON data from jQuery

I am trying to use ajaxFIleUpload in my website. I am not recieving JSON data send by JavaScript to PHP. I am stuck at this point. File Uploading is ok but i am not able to recieve any post values. My jQuery function is
$(function() {
$(document).on("submit", "#upload_file", function(e) {
e.preventDefault();
$.ajaxFileUpload({
url :base_url + 'payments/uploadPaymentSlip/',
secureuri :false,
fileElementId :'userfile',
type : 'POST',
data: { paymentFormInputAmount: 'asdasd' },
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
//refresh_files();
$('#files').val('');
}
alert(data.msg);
},
dataType: 'json'
});
});
});
My PHP Function is
function uploadPaymentSlip() {
$status = "";
$msg = "";
$file_element_name = 'userfile';
$status = "error";
// checking whether json value shows in php or not
// $_POST['paymentFormInputAmount'] is also not working
$msg = $_POST['paymentFormInputAmount'];
if ($status != "error") {
$config['upload_path'] = realpath( APPPATH . '../uploads/paymentSlip' );
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name)) {
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else {
$data = $this->upload->data();
// $file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
if($file_id) {
$status = "success";
$msg = "File successfully uploaded";
}
else {
unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
type: 'json' must be type: 'POST'
and you should add:
contentType: 'json',
dataType: 'json'
as parameter to $.ajaxFileUpload
contentType means you are sending your data as json.
dataType means you are expecting result as type of json.

Codeigniter 2.1 - multiple file upload doesn't work

I have bit of a problem. When I select to upload one image, function works. But for the multiple images it doesn't work and I get error
You did not select a file to upload.
(Fields for more images upload are created via JS, if user enter correct code. If code is not entered or if it is wrong original input is used for selecting a file).
What seems to be a problem?
Controller function:
function img_upload($folder) {
$this->path = './public/img/' . $folder;
$imgs = array();
$config = array(
'allowed_types' => 'jpg|jpeg|png|gif',
'upload_path' => $this->path
);
$CI = &get_instance();
$CI->load->library('upload', $config);
foreach ($_FILES as $key => $value) {
if (!$CI->upload->do_upload($key)) {
return $error = implode(',',array('error' => $CI->upload->display_errors()));
} else {
$q = $CI->upload->data();
$config['image_library'] = 'gd2';
$config['source_image'] = $this->path . '/' . $q['file_name'];
$config['new_image'] = $this->path . '/thumbs';
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 128;
$config['height'] = 128;
$CI->load->library('image_lib');
$CI->image_lib->clear();
$CI->image_lib->initialize($config);
$CI->image_lib->resize();
array_push($imgs, $q['file_name']);
}
}
if(empty($imgs)){
return FALSE;
} else {
return implode(',', $imgs);
}
}
Part of HTML for selecting file:
<label for="image">Slika</label><input type="file" name="userfile" id="image" />
JS for adding new fields:
code.on('focusout', function(){
if(!$(this).val())
{
$('label[for^=image_paid], input[id^=image_paid], input[name=time]').remove();
}
if(!$('#image4').length > 0)
{$.ajax({
type: 'POST',
url: '<?php echo base_url() ?>global_info/gi_get_ad_payment_code',
data: 'code=' + code.val(),
success: function(data){
for(i = 1; i<=4; i++)
{
$('#image').after('<label for="image' + i +'">Slika</label><input type="file" name="userfile" id="image' + i +'" />');
}
code.after('<input type="hidden" name="time" value="'+ data +'" />');
code.after('<input type="hidden" name="paid" value="1" />');
},
error: function(){
alert('nije uspeh');
}
}); /* KRAJ NA AJAX */
};/* KRAJ NA IF */
});
IF you don't mind use this plugin. It will work great....I have used it many times ..http://www.plupload.com/

Categories