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
Related
I'm trying to upload an image to a folder using ajax, jquery and php but the problem is that I don't know how to send my file input value to my php file, when I run my code I get the following message:
undefined index archivo
This is my ajax call (PD. All the other parameters works properly, I only have problems with the file input value)
function Registrar() {
var cat = $('#cat').val();
var nom = $('#name').val();
var desc = $('#description').val();
var image = $('#archivo').val();
//Also tried with this, to remove the fakepath string... $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')
$.ajax({
url: '../../class/upload.php',
method: 'POST',
data: { categoria: cat, nombre: nom, descripcion: desc, archivo: image, activo: act, disponible: disp, precio: prec },
success: function (data) {
console.log(data);
}
});
}
PHP file:
<?php
$categoria = $_POST['categoria'];
$nombre = $_POST['nombre'];
$descripcion = $_POST['descripcion'];
$img = $_POST['archivo'];
$activo = $_POST['activo'];
$disponible = $_POST['disponible'];
$precio = $_POST['precio'];
$IdCategoria = 0;
$filepath = "";
//Imagen
if($categoria=="Piano") {
$IdCategoria = 1;
$filepath = "../Files/Productos/Piano/".$img;
}
$filetmp = $_FILES['archivo']['tmp_name'];
move_uploaded_file($filetmp, $filepath);
echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;
?>
And the important parts of my HTML:
<form id="registerForm" method="post" role="form" enctype="multipart/form-data" >
<input name="archivo" id="archivo" style="width: 70%;" name="textinput" class="btn btn-block" type="file" onchange="showimagepreview(this)" />
EDIT: showimagepreview
function showimagepreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
How can I solve this?
Send your form data like this:
var formData = new FormData($("form")[0]);
$.ajax({
url: '../../class/upload.php',
method: 'POST',
data: formData,
success: function (data) {
console.log(data);
}
});
And you have to get the file with $_FILES, you can not get it in $_POST in php code.
Here is you solution
HTML
<form id="registerForm" method="post" enctype="multipart/form-data">
<input name="archivo" id="archivo" style="width: 70%;" class="btn btn-block" type="file" onchange="PreviewImage(this)" />
<img id="uploadPreview" />
<button type="submit">Submit</button>
Java Script
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("image").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview").src = oFREvent.target.result;
};
};
//ajax
$("#registerForm").submit(function(event) {
var formData = new FormData($(this)[0]);
if ($(this).valid()) {
$.ajax({
url : '../../class/upload.php',
type : 'POST',
data : formData,
contentType : false,
cache : false,
processData : false,
success: function(e) {alert(e) },
error : function(x, t, m) {},
});
}
});
PHP
<?php
echo "<pre>"; print_r($_FILES);echo "</pre>"; die; //this will show you the file transfered by form.
$categoria = $_POST['categoria'];
$nombre = $_POST['nombre'];
$descripcion = $_POST['descripcion'];
$img = $_POST['archivo'];
$activo = $_FILES['activo'];
$disponible = $_POST['disponible'];
$precio = $_POST['precio'];
$IdCategoria = 0;
$filepath = "";
//Imagen
if($categoria=="Piano") {
$IdCategoria = 1;
$filepath = "../Files/Productos/Piano/".$img;
}
$filetmp = $_FILES['archivo']['tmp_name'];
move_uploaded_file($filetmp, $filepath);
echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;
?>
change this
$img = $_POST['archivo'];
to
$_FILES['archivo'];
Files object cannot be recieved in $_POST
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
im having trouble in uploading a multiple file by ajax . here is my code.
HTML code:-
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="button" id="uploadBusinessImg" value="Upload" >
Ajax Code:-
$("#uploadBusinessImg").on("click",function(e)
{
var fd = new FormData();
var file_data = $("#txtBusinessImage")[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file"+[i], file_data[i]);
}
var other_data = $("#selectBusinessHiddenID").serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
data: fd,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
When im calling upload_business_photo_do() function via Ajax then it does't able to recive the name of image $_FILES['file']['name']
upload_business_photo_do()
{
$business_hidden_id=$this->input->post('selectBusinessHiddenID');
/*code for image*/
$config['upload_path']='./upload_101/';
$config['allowed_types']= 'jpg|png|jpeg';
$config['max_width'] = '6000';
$config['max_height'] = '4500';
$this->load->library('upload',$config);
for($i=0; $i<count($_FILES['file']['name']); $i++)
{
$_FILES['userfile']['name']= $_FILES['file']['name'][$i];
$_FILES['userfile']['type']= $_FILES['file']['type'][$i];
$_FILES['userfile']['tmp_name']= $_FILES['file']['tmp_name'][$i];
$_FILES['userfile']['error']= $_FILES['file']['error'][$i];
$_FILES['userfile']['size']= $_FILES['file']['size'][$i];
if(! $this->upload->do_upload())
{
/*----set flash message*/
echo "error";
}
else
{
echo "done";
}
}
}
try to use like this , its simple and easy
$("#uploadBusinessImg").on("click",function(e)
{
var formData = new FormData($("#form_name")[0]);
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
processData: false,
contentType: false,
data: formData,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
and in controller use like this
if($_FILES['txtBusinessImageName'])
{
$file_ary = $this->reArrayFiles($_FILES['txtBusinessImageName']);
foreach ($file_ary as $file)
{
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
and also use this function for convert files data into array for multiple images data
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
its working perfect , just try to use it . you don't need to add a extra codes of files with ajax.
use form tag and submit button for file upload.
<form method="post" enctype="multipart/form-data">
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="submit" id="uploadBusinessImg" value="Upload">
</form>
and remove enctype: 'multipart/form-data', from ajax call and try.
Change following for fetching files:
var file_data = $('#txtBusinessImage').prop('files')[0];
var fd = new FormData();
fd.append('file', file_data);
Am using PHP to create thumbnail from following code but when i run code i get following ERROR
Notice: Undefined variable: phpThumb in C:\Users\logon\Documents\NetBeansProjects\rename multiple file with rename frm single input\for.php on line 42
Fatal error: Call to a member function setSourceFilename() on a non-object in C:\Users\logon\Documents\NetBeansProjects\rename multiple file with rename frm single input\for.php on line 42
since am uploading multiple file how do i create thumb for all formate images
PHP processing code for uploading multiple image and creating thumb
<?php
$newname = uniqid() . '_' . time();
$file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null;
$file2 = isset($_FILES['files']['name'][1]) ? $_FILES['files']['name'][1] : null;
$file3 = isset($_FILES['files']['name'][2]) ? $_FILES['files']['name'][2] : null;
$file4 = isset($_FILES['files']['name'][3]) ? $_FILES['files']['name'][3] : null;
$file5 = isset($_FILES['files']['name'][4]) ? $_FILES['files']['name'][4] : null;
if (isset($_FILES['files'])) {
$errors = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$file_name = $key . $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data";
if (empty($errors) == true) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (is_dir("$desired_dir/" . $file_name) == false) {
move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
} else { // rename the file if another one exist
$new_dir = "$desired_dir/" . $newname . $file_name;
rename($file_tmp, $new_dir);
}
} else {
print_r($errors);
}
}
if (empty($error)) {
echo "FILE : $file1<br>";
echo "FILE : $file2<br>";
echo "FILE : $file3<br>";
echo "FILE : $file4<br>";
echo "FILE : $file5<br>";
//thumb creation
$files = array("$file1", "$file1", "$file1", "$file1", "$file1");
foreach ($files as $file) { // here's part 1 of your answer
$phpThumb->setSourceFilename($file);
$phpThumb->setParameter('w', 100);
$outputFilename = "thumbs/" . $file;
if ($phpThumb->GenerateThumbnail()) {
if ($phpThumb->RenderToFile($outputFilename)) { // here's part 2 of your answer
// do something on success
} else {
//failed
}
} else {
// failed
}
}
}
}
?>
Edited again to reflect the posters new wishes of how the user experience should be. Now has a drag-drop with preview OR manual selection of 5 files. The drag-drop is submitted by a ajax post, so watch the console for the result. Display and flow needs to be streamlined, but shows a technical working example. The same PHP code handles both results.
<html>
<body>
<pre><?
print_r($_FILES); //SHOW THE ARRAY
foreach ($_FILES as $file) {
if (!$file['error']) {
//PROCESS THE FILE HERE
echo $file['name'];
}
}
?></pre>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var fd = new FormData();
$(document).ready(function() {
//submit dragdropped by ajax
$("#dropsubmit").on("click", function(e) {
$.ajax({
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
//FILES POSTED OK! REDIRECT
console.log(data);
}
});
})
var dropzone = $("#dropzone");
dropzone.on('dragenter', function (e) {
$(this).css('background', 'lightgreen');
});
//dropped files, store as formdata
dropzone.on('dragover', stopPropagate);
dropzone.on('drop', function (e) {
stopPropagate(e)
$(this).css('background', 'white');
var files = e.originalEvent.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
preview(files[i])
fd.append('file' + (i + 1), files[i]);
if (i >= 5) continue
}
});
function stopPropagate(e) {
e.stopPropagation();
e.preventDefault();
}
if (window.File && window.FileList && window.FileReader) {
$("input[type=file]").on("change", function(e) {
preview(e.target.files[0])
});
} else {
alert("Your browser doesn't support to File API")
}
function preview(item) {
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<img></img>", {
class: "imageThumb",
src: file.result,
title: file.name,
}).appendTo("#images");
});
fileReader.readAsDataURL(item);
}
});
</script>
<div id="dropzone" style="width:100px;height:100px;border:2px dashed gray;padding:10px">Drag & Drop Files Here</div>
<input type="button" id="dropsubmit" value="Submit dropped files" />
<hr>
<form method="post" enctype="multipart/form-data">
<input id="file1" name="file1" type="file"/><br>
<input id="file2" name="file2" type="file"/><br>
<input id="file3" name="file3" type="file"/><br>
<input id="file4" name="file3" type="file"/><br>
<input id="file5" name="file3" type="file"/><br>
<input name="submit" type="submit" value="Upload files" />
</form><div id="images"></div>
</body>
</html>
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/