How to replace old file with new file in codeigniter? - php

I am using unlink to remove old file with new file, but it doesn't work. Please help me, I'm a new programmer and really stuck with this.
here's my code
if ($data['upload_spk'] = "") {
$config['upload_path'] = './assets/upload';
$config['allowed_types'] = 'jpg|png|pdf';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('upload_spk')) {
echo "upload gagal";
die();
} else {
$data['upload_spk'] = $this->upload->data('file_name');
$id_ajukan = $this->input->post('id_ajukan');
$query = $this->db->get('ajukan_keluhan', array('id_ajukan' => $id_ajukan));
$ambil = $query->row()->upload_spk;
unlink('./assets/upload/' . $ambil);
}
} else {
if ($_FILES['upload_spk']['name'] != "") {
$config['upload_path'] = './assets/upload';
$config['allowed_types'] = 'jpg|png|pdf';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('upload_spk')) {
echo "upload gagal";
die();
} else {
//upload_spk diubah
$data['upload_spk'] = $this->upload->data('file_name');
$id_ajukan = $this->input->post('id_ajukan');
$query = $this->db->get('ajukan_keluhan', array('id_ajukan' => $id_ajukan));
$ambil = $query->row()->upload_spk;
unlink('./assets/upload/' . $ambil);
}
} else {
$data['upload_spk'] = $this->input->post('lama');
}
}
and this is code in view
<div class='form-group row'> <label for='uploadsp' class='col-sm-2 col-form-label'>Upload SP/SPK</label> <div class='col-sm-10' align='left'> <input type='file' class='form-control col-md-10' cols='10' rows='5' name='upload_spk' / accept='.jpg, .png, .pdf/*'><input type='hidden' id='lama' name='lama' value='<?= $kelola_tiket->upload_spk ?>'> </div> </div>

Related

File not selected in form multiple upload in Codeigniter

so i try to make some upload form which will upload some image. but when the image has chosen then the button submit has clicked the result say "You did not select a file to upload."
im using php, with codeigniter framework
The view
<form class="text-left" enctype="multipart/form-data" method="post" action="<?= base_url('aduan/add'); ?>">
<div class="form-group">
<label>Upload Foto Bukti Aduan</label>
<div class="form-group">
<label>Bukti Aduan 1</label>
<input class="form-control-file" type="file" id="bukti1" name="bukti_aduan1" />
<?= form_error('bukti_aduan1', '<p class="text-danger font-weight-bold pl-2">', '</p>'); ?>
</div>
<div class="form-group">
<label>Bukti Aduan Pelapor di Lokasi</label>
<input class="form-control-file" type="file" id="bukti2" name="bukti_aduan2" />
<?= form_error('bukti_aduan2', '<p class="text-danger font-weight-bold pl-2">', '</p>'); ?>
</div>
</div>
which the view will run the controller "aduan" for input function
Controller file:
$aduan = $this->aduan_model;
$validation = $this->form_validation;
$validation->set_rules($aduan->rules());
if ($validation->run()) {
$aduan->tambah();
$this->session->set_flashdata('success', 'Berhasil disimpan');
$data['title'] = 'Buat Aduan Kasus Lingkungan';
$this->load->view('home/home_header', $data);
$this->load->view('home/aduansukses');
$this->load->view('home/home_footer');
} else {
$data['aduan'] = $this->aduan_model->getAll();
$data['title'] = 'Buat Aduan Kasus Lingkungan';
$this->load->view('home/home_header', $data);
$this->load->view('home/buataduan');
$this->load->view('home/home_footer');
}
then the controller will load a model which is "aduan_model"
Model file :
public function tambah()
{
$post = $this->input->post();
$this->nik_pelapor = $post["nik_pelapor"];
$this->nama_pelapor = $post["nama_pelapor"];
$this->email_pelapor = $post["email_pelapor"];
$this->telp_pelapor = $post["telp_pelapor"];
$this->alamat_pelapor = $post["alamat_pelapor"];
$this->aduan = $post["aduan"];
$this->bukti_aduan1 = $this->_uploadImage();
$this->bukti_aduan2 = $this->_uploadImage2();
$this->status_aduan = 'Dalam proses';
$this->tgl_aduan = time();
$this->db->insert($this->_table, $this);
}
private function _uploadImage()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
// $config['max_width'] = 1024;
// $config['max_height'] = 768;
$this->load->library('upload', $config);
if ($this->upload->do_upload('bukti_aduan1')) {
return $this->upload->data();
}
return "default.jpg";
}
private function _uploadImage2()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
// $config['max_width'] = 1024;
// $config['max_height'] = 768;
$this->load->library('upload', $config);
if ($this->upload->do_upload('bukti_aduan2')) {
return $this->upload->data();
}
return "default.jpg";
}
i expect the output of image can be stored in file upload and inserted in database but it doesnt select any file
please help :)
try my code
replace if condition in controller to upload
if(
(!$this->upload->do_upload('bukti_aduan2')) &&
(! $this->upload->do_upload('bukti_aduan1'))
)
{
echo "failed";
}
else
{
echo "success";
}

Multiple File Upload Controls not working in CI

In CodeIgniter, I have 4 file upload controls as under:
<?php echo form_open_multipart('uploadimg');?>
<input type="file" name="image1" />
<input type="file" name="image2" />
<input type="file" name="image3" />
<input type="file" name="image4" />
<input type="submit" value="upload" />
<?php echo form_close();?>
Following is my file upload code:
$name1="img1.jpg";
$config1=array(
'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/c/uploads/",
'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite'=>TRUE,
'max_size'=>"500",
'file_name'=>$name1,
);
$this->load->library('upload',$config1);
if($this->upload->do_upload('image1'))
{
echo "Image 1 has been uploaded successfully";
}
else
{
echo $this->upload->display_errors();
}
$name2="img2.jpg";
$config2=array(
'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/c/uploads/",
'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite'=>TRUE,
'max_size'=>"500",
'file_name'=>$name2,
);
$this->load->library('upload',$config2);
if($this->upload->do_upload('image2'))
{
echo "Image 2 has been uploaded successfully";
}
else
{
echo $this->upload->display_errors();
}
$name3="img3.jpg";
$config3=array(
'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/c/uploads/",
'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite'=>TRUE,
'max_size'=>"500",
'file_name'=>$name3,
);
$this->load->library('upload',$config3);
if($this->upload->do_upload('image3'))
{
echo "Image 3 has been uploaded successfully";
}
else
{
echo $this->upload->display_errors();
}
$name4="img4.jpg";
$config4=array(
'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/c/uploads/",
'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite'=>TRUE,
'max_size'=>"500",
'file_name'=>$name4,
);
$this->load->library('upload',$config4);
if($this->upload->do_upload('image4'))
{
echo "Image 4 has been uploaded successfully";
}
else
{
echo $this->upload->display_errors();
}
I am getting the following output:
Image 1 has been uploaded successfullyImage 2 has been uploaded
successfullyImage 3 has been uploaded successfullyImage 4 has been
uploaded successfully
But, in the uploads folder, I am getting only 1 file. Strange thing is that the file that is being shown is of last file upload control, but the name of file is img1., i.e. name of first uploaded file.
Why is this happening? What is the solution?
Set each config using the initialize() method and not when loading the upload library.
Changed:
$this->load->library('upload', $config*);
To:
$this->upload->initialize($config*);
Updated code:
$this->load->library('upload');
$name1 = "img1.jpg";
$config1 = array(
'upload_path' => FCPATH . "uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite' => TRUE,
'max_size' => "500",
'file_name' => $name1
);
$this->upload->initialize($config1);
if ($this->upload->do_upload('image1')) {
echo "Image 1 has been uploaded successfully";
} else {
echo $this->upload->display_errors();
}
$name2 = "img2.jpg";
$config2 = array(
'upload_path' => FCPATH . "uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite' => TRUE,
'max_size' => "500",
'file_name' => $name2
);
$this->upload->initialize($config2);
if ($this->upload->do_upload('image2')) {
echo "Image 2 has been uploaded successfully";
} else {
echo $this->upload->display_errors();
}
$name3 = "img3.jpg";
$config3 = array(
'upload_path' => FCPATH . "uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite' => TRUE,
'max_size' => "500",
'file_name' => $name3
);
$this->upload->initialize($config3);
if ($this->upload->do_upload('image3')) {
echo "Image 3 has been uploaded successfully";
} else {
echo $this->upload->display_errors();
}
$name4 = "img4.jpg";
$config4 = array(
'upload_path' => FCPATH . "uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite' => TRUE,
'max_size' => "500",
'file_name' => $name4
);
$this->upload->initialize($config4);
if ($this->upload->do_upload('image4')) {
echo "Image 4 has been uploaded successfully";
} else {
echo $this->upload->display_errors();
}
You may try this. This is working properly to upload two file
(audio, image) or more file to the database.
Table Name : products
| id | product_name | price | description| product_image | audio_file |
HTML
<form name="addProduct" id="addProduct" method="POST" enctype="multipart/form-data">
<input type="text" name="product_name" placeholder="Product Name">
<input type="text" name="price" placeholder="Product Price">
<textarea id="description" name="description" class="materialize-textarea" placeholder="Description"></textarea>
<input type="file" name="product_image" id="fileImg">
<input type="file" name="audio_file" id="audio_file">
<input type="button" name="addProduct" value="Add Product" class="btn btn-flat btn-add-product">
</form>
Controller
public function addProducts(){
/*Initialization of model*/
$this->load->model("product_model");
/*store data into array*/
$result=array(
"product_name"=>$_POST["product_name"],
"price"=>$_POST["price"],
"description"=>$_POST["description"],
);
$proID = $this->product_model->addProduct($result); //sending data to model for insertion
//Define the file names with blog id with same extension which has been uploaded
$product_image = $proID."_product.".pathinfo($_FILES['product_image']['name'], PATHINFO_EXTENSION);
$product_audio = $proID."_audio.".pathinfo($_FILES['audio_file']['name'], PATHINFO_EXTENSION);
$updateData = array(
"product_image" => $product_image,
"audio_file"=>$product_audio
);
// update the name of the images in the database
$this->product_model->updateProduct($updateData,$proID);
//set configuration for the upload library
/* |===> Image Config <==|*/
$config['upload_path'] = 'html/images/products/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = TRUE;
$config['encrypt_name'] = FALSE;
$config['remove_spaces'] = TRUE;
/* |==> Audio Config <==|*/
$config_audio['upload_path'] = 'html/images/products/audios/';
$config_audio['allowed_types'] = 'mp3|mp4';
$config_audio['overwrite'] = TRUE;
$config_audio['encrypt_name'] = FALSE;
$config_audio['remove_spaces'] = TRUE;
//set name in the config file for the feature image
$config['file_name'] = $proID."_product";
$this->load->library('upload', $config); // config first file
$this->upload->do_upload('product_image');
$this->upload->display_errors();
$config_audio['file_name'] = $proID."_audio";
$this->upload->initialize($config_audio); // config seconf file
$this->upload->do_upload('audio_file');
$this->upload->display_errors();
}
Model
/*Add Product*/
public function addProduct($pro_data){
$query=$this->db->insert("products",$pro_data);
$id=$this->db->insert_id();
return $id;
}
/*Update for Multiple File Upload*/
public function updateProduct($result,$up_id){
$this->db->where('id',$up_id);
$this->db->update("products",$result);
}
This is working nicely to my website and i hope it will help you to boost your code.
HTML
<form class="col s12" id='propertyform' enctype="multipart/form-data">
<input type="file" name="image1" />
<input type="file" name="image2" />
<input type="file" name="image3" />
<input type="file" name="image4" />
<a class="waves-effect waves-light btn addproperty">add</a>
</form>
js
$(".addproperty").on("click",function()
{
var baseurl = $("#base_url").val();
var property = new FormData($("#propertyform")[0]);
$.ajax({
url : baseurl+"dropdowns/add_propertyy",
data : property,
type:"POST",
contentType:false,
processData:false,
success:function(res)
{
window.location.reload();
}
});
});
controller
public function add_propertyy()
{
$id = 1;
$images = $id."_image1.".pathinfo($_FILES['image1']['name'], PATHINFO_EXTENSION);
$images1 = $id."_image2.".pathinfo($_FILES['image2']['name'], PATHINFO_EXTENSION);
$images2 = $id."_image3.".pathinfo($_FILES['images3']['name'], PATHINFO_EXTENSION);
$images3 = $id."_image4.".pathinfo($_FILES['image4']['name'], PATHINFO_EXTENSION);
$addimg = array(
"images1" => $images,
"images2" => $images1,
"images3" => $images2,
"images4" => $images3,
);
$this->load->model('property_model');
$this->property_model->add_pro_img($addimg,$id);
$uploadPath = "./html/images/property";
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf';
$config['overwrite'] = TRUE;
$config['encrypt_name'] = FALSE;
$config['remove_spaces'] = TRUE;
$config['file_name'] = $id."_images1";
$this->load->library('upload', $config);
$this->upload->do_upload('images');
$this->upload->display_errors();
$config['file_name'] = $id."_images2";
$this->upload->initialize($config);
$this->upload->do_upload('images2');
$this->upload->display_errors();
$config['file_name'] = $id."_images3";
$this->upload->initialize($config);
$this->upload->do_upload('images3');
$this->upload->display_errors();
$config['file_name'] = $id."_images4";
$this->upload->initialize($config);
$this->upload->do_upload('images4');
$this->upload->display_errors();
}
modal
public function add_pro($data) {
$this->db->insert("property",$data);
$id = $this->db->insert_id();
return $id;
}

Couldn't upload photo in php

I am using CodeIgniter framework for PHP.And I couldn't upload/update a photo.
Here is the edit-profile1.php View:
<form action="<?php echo base_url(); ?>users/update/" method="post" enctype="multipart/form-data" data-toggle="validator">
<div class="container">
<div class="padd col-xs-12 col-md-3">
<label class="label">My IC/Matric Card</label></br>
<input name="image" placeholder="Upload" class="upload friendly" type="file" accept="image/*" capture="environment" required>
</div>
<div class="col-xs-12 col-md-9 padd" style="overflow:auto;">
<div class="picture"><img id="blah" style="width: 100%; height: 100%"
<?php
if($userdata[0]['image'] == "")
{
echo "src='https://style.anu.edu.au/_anu/4/images/placeholders/person.png'";
}else{
echo "src='" . str_replace('/index.php/','/',base_url())."media/images/users/".$userdata[0]['image']."'";
}
?> >
</div>
</div>
</div>
<div class="container">
<div class="row">
<div>
<button type="submit" style='width: 100%; margin-top:20px; margin-bottom: 20px !important; background-color: #59d389; color: white;' class="btn btn-responsive btn-md center-block">Save Changes</button>
<input type="hidden" value="<?php echo $userdata[0]['id']; ?>" name="id" />
<input type="hidden" value="<?php echo $userdata[0]['account_status']; ?>" name="id" />
<input type="hidden" value="<?php echo $userdata[0]['image']; ?>" name="oldimage"/>
</div>
</div>
</div>
</form>
Here is the Users.php Controller:
public function profile()
{
$data['userdata'] = $this->usermodel->get_user($this->session->userdata('id'));
$this->load->view('edit-profile1',$data);
}
public function update()
{
$user = new Users_model();
// $user->phone1 = $this->input->post('phone1');
$user->account_status = 1;
//session data
$user->id = $this->session->userdata('id');
$user->password = $this->session->userdata('password');
$user->username = $this->session->userdata('username');
$user->email = $this->session->userdata('email');
$user->user_role = $this->session->userdata('user_role');
//id to be set
$id = $user->id;
if($_FILES['image'])
{
/* IMAGE UPLOADING START */
$image_type=$_FILES['image']['type'];
$image_size=$_FILES['image']['size'];
$image_tmp=$_FILES['image']['tmp_name'];
$d=date('YmdHis');
//$image_test_name = str_replace(" ", "_", $user->firstname.$user->lastname);
$image_type = str_replace("image/", ".", $image_type);
$image_name=$user->id . $image_type;
$imgurl= str_replace("/index.php/","/",base_url())."media/images/users/".$image_name;
if($image_type==".jpeg" || $image_type==".png" || $image_type==".gif" )
{
$this->usermodel->upload_user_image($image_name);
$this->usermodel->update_image($user->id, $image_name);
$user->image = $image_name;
}
else
{
$user->image = $this->input->post('oldimage');
}
/* IMAGE UPLOADING END */
}else{
$user->image = $this->input->post('oldimage');
}
$res = $this->db->update('users', $user, array('id' => $id));
$URL = base_url() . "users/profile/";
redirect($URL, "refresh");
}
}
And here is the Users_model.php Model:
public function upload_user_image($image_name) {
$config['upload_path'] = 'media/images/users';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['overwrite'] = TRUE;
$config['file_name'] = $image_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image')) {
$this->upload->display_errors('<span>', '</span>');
$data['error'] = $this->upload->display_errors();
} else {
$file_data = $this->upload->data();
$data['success'] = "Your file is uploaded";
}
}
public function update_image($id,$image_name){
$sql = "update users set image = '$image_name' where id = $id ";
$this->db->query($sql);
}
When the page redirect, the image is uploaded. The problem is, when refreshing manually, the placeholder image appear again and it means the photo wasn't updated to the database.
Here is the link to the website: https://www.yiyalo.com
You can log in using these credentials
id: qy_leong13#hotmail.com
pass: 123456
GO to My account > My profile to try it out
You need to upload file in controller itself. If you are using file upload library then don't need to do it manually with $_FILES variable.
public function update()
{
$user = new Users_model();
// $user->phone1 = $this->input->post('phone1');
$user->account_status = 1;
//session data
$user->id = $this->session->userdata('id');
$user->password = $this->session->userdata('password');
$user->username = $this->session->userdata('username');
$user->email = $this->session->userdata('email');
$user->user_role = $this->session->userdata('user_role');
//id to be set
$id = $user->id;
$config['upload_path'] = 'media/images/users';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['overwrite'] = TRUE;
//$config['file_name'] = $image_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image')) {
$this->upload->display_errors('<span>', '</span>');
$data['error'] = $this->upload->display_errors();
} else {
$file_data = $this->upload->data();
$data['success'] = "Your file is uploaded";
}
$res = $this->db->update('users', $user, array('id' => $id));
$URL = base_url() . "users/profile/";
redirect($URL, "refresh");
}

Getting "The filetype you are attempting to upload is not allowed." in codeigniter while uploading video

I am stuck here.. I was trying to upload image and video, image upload working fine but while uploading video getting the error as "The filetype you are attempting to upload is not allowed.". I have tried all the answers but unfortunately couldn't workout. Can someone plz help me. What Am I doing wrong? Thanks.
My View 'home':
<div style="margin-right: 17px;">
<label>Name:</label>
<input type="text" name="name" value="<?php echo set_value('name');?>">
<?php echo form_error('name','<div class="error">','</div>'); ?>
</div>
<div style="padding:20px 20px">
<label>Upload Image</label>
<input type="file" name="photo">
</div>
<div style="padding:5px 5px">
<label>Upload Video</label>
<input type="file" name="video">
</div>
<div style="padding:10px 10px">
<input type="submit" name="sumit" value="Submit">
</div>
</form>
My Controller:
$this->form_validation->set_rules('name', 'Name', 'trim|required');
if(! $this->form_validation->run()){
$data['useradded'] = "";
}
else{
if(isset($_FILES['photo']['tmp_name'])){
$config['upload_path'] = "./uploads/complaints/";
$config['allowed_types'] = "jpg|png|gif";
$config['max_size'] = '2048';
$config['max_width'] = '0';
$config['max_height'] = '0';
$new_name = "photo_" . rand();
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
if(! $this->upload->do_upload('photo')){
$data['error'] = array('error' => $this->upload->display_errors());
$photo_name = "";
}else{
$photo_name = $new_name;
}
}
if(isset($_FILES['video']['tmp_name'])){
$config['upload_path'] = "./uploads/complaints/videos/";
$config['allowed_types'] = "avi|flv|wmv|mpg|mpeg|mp3|mp4";
//$config['allowed_types'] = "video/x-msvideo|image/jpeg|video/mpeg|video/x-ms-wmv";
$config['max_size'] = '0';
$new_name = "video_" . rand();
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
if(! $this->upload->do_upload('video')){
$data['error'] = array('error' => $this->upload->display_errors());
$video_name = "";
}else{
$video_name = $new_name;
}
}
$this->complaints_model->add_complaint($photo_name,$video_name);
$data['useradded'] = "New complaint added Successfully";
}
$this->load->view('home', $data);

Upload multiple files in CodeIgniter not work

in my CodeIgniter project I'm uploading files during the project creation. Here's the uploading function:
public function addProcess()
{
echo 'test';
if($this->input->server('REQUEST_METHOD') === 'POST')
{
$this->form_validation->set_rules('album', 'Album', 'trim|required|callback_check_select', 'xss_clean');
if ($this->form_validation->run() === FALSE)
{
$data['albums'] = $this->album_model->albumList();
$this->adminTheme('admin/addSong',$data);
}
else
{
$error = 0;
$this->load->library('upload');
$total_count_of_files = count($_FILES['userfile']['name']);
$album = $this->input->post('album');
$songs = $this->input->post('song');
$artist = $this->input->post('artist');
for($i=0; $i< $total_count_of_files; $i++)
{
if(!$songs[$i])
$songs[$i] = "Track-".($i+1);
if(!$artist[$i])
$artist[$i] = " ";
$_FILES['file']['name'] = $_FILES['userfile']['name'][$i];
$_FILES['file']['type'] = $_FILES['userfile']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['userfile']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['userfile']['error'][$i];
$_FILES['file']['size'] = $_FILES['userfile']['size'][$i];
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|jpeg|gif|png|mp3';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$config['encrypt_name'] = TRUE;
$this->upload->initialize($config);
if($this->upload->do_upload('file'))
{
$msg = $this->upload->data();
$name = $msg['file_name'];
$error += 0;
$this->song_model->add($songs[$i], $artist[$i], $name, $album);
}else{
$errorStr[] = "$songs[$i] Upload Faild";
$error += 1;
}
}
//$this->album_model->add();
if($error == 0)
{
//$this->msg('admin/song','Successfully added..Redirecting now...');
}
else
{
$this->msg('admin/song','Successfully added..Redirecting now...');
}
}
}
else
{
redirect('admin/album');
}
}
another function for doupload
public function do_upload()
{
$upload_path_url = base_url().'uploads/';
$config['upload_path'] = FCPATH.'uploads/';
$config['allowed_types'] = 'jpg|jpeg|gif|png|mp3';
$config['max_size'] = '30000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload', $error);
} else {
$data = $this->upload->data();
$info->name = $data['file_name'];
$info->size = $data['file_size'];
$info->type = $data['file_type'];
$info->url = $upload_path_url .$data['file_name'];
$info->thumbnail_url = $upload_path_url .$data['file_name'];
$info->delete_url = base_url().'upload/deleteImage/'.$data['file_name'];
$info->delete_type = 'DELETE';
if (IS_AJAX) {
echo json_encode(array($info));
} else {
$file_data['upload_data'] = $this->upload->data();
$this->load->view('admin/upload_success', $file_data);
}
}
}
my form code
<div id="container">
<h2>Song Name - Add New</h2>
<div class="error">
<?php echo validation_errors(); ?>
</div>
<?php $attributes = array('id' => 'myform'); ?>
<?php echo form_open_multipart('admin/song/addProcess',$attributes); ?>
<div class="line">
<label style="width: 160px;">Album:</label>
<select class="category" name="album" style="width: 280px;">
<option value="select">Select Album</option>
<?php foreach($albums as $album): ?>
<option value="<?php echo $album['id']; ?>">
<?php echo $album['root_name']." --> ".$album['category_name']." --> ".$album['album_name']; ?></option>
<?php endforeach ?>
</select>
<input class="form-submit" style="margin-top: 6px;" type="button" id="more_fields" onclick="add_fields();" value="Add More" />
</div>
<!--end line-->
<div id="nameFields">
<div class="line">
<input type="text" name="song[]" class="input1" style="width: 180px;" placeholder="Song Name" />
<input type="text" name="artist[]" class="input1" style="width: 180px;" placeholder="Artist Name" />
<input type="file" name="userfile[]" class="category" style="width:80px;" />
</div>
<!--end line-->
</div>
<input type="submit" value="Save" class="form-submit" style="margin-right: 180px;" />
</form>
</div>
<!--end container-->
<script type="text/javascript">
function add_fields() {
document.getElementById('nameFields').innerHTML += "<div class='line'><input type='text' name='song[]' class='input1' style='width: 180px;' placeholder='Song Name' /><input type='text' name='artist[]' class='input1' style='width: 180px;' placeholder='Artist Name' /><input type='file' name='userfile[]' class='category' style='width:80px;' /></div>";
}
</script>
However this does not do anything. The files are not being uploaded. Even an empty directory is not being created. Could anybody help me to find the error?
Thanks.
In your addProcess code, remove below code
$_FILES['file']['name'] = $_FILES['userfile']['name'][$i];
$_FILES['file']['type'] = $_FILES['userfile']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['userfile']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['userfile']['error'][$i];
$_FILES['file']['size'] = $_FILES['userfile']['size'][$i];
and try
foreach ($_FILES as $fieldname => $fileObject)
{
if (!empty($fileObject['name']))
{
$this->upload->initialize($config);
if (!$this->upload->do_upload($fieldname))
{
$errors[] = $this->upload->display_errors();
}
else
{
//success code
}
}
}

Categories