I am trying to insert 1 image in 2 different directories but it is saving only in the first directory but not in the second directory.I am unable find the mistake in my code,please check the below code and help us.Thanks in advance.
public function image()
{
$data = array();
$error = array();
$config1=array(
'upload_path'=>'upload/',
'allowed_types'=>'jpg|jpeg|png|bmp',
'max_size'=>0,
'filename'=>url_title($this->input->post('file'))
);
$this->load->library('upload',$config1);
if($this->upload->do_upload('file')){
$error = array('error' => $this->upload->display_errors());
echo "<pre>";
print_r($error);
exit();
}else {
$fdata = $this->upload->data();
$data['image'] = 'upload/' . $fdata['file_name'];
}
$config2=array(
'upload_path'=>'upload/images/',
'allowed_types'=>'jpg|jpeg|png|bmp',
'max_size'=>0,
'filename'=>url_title($this->input->post('file'))
);
$this->upload->initialize($config2);
if (!$this->upload->do_upload('file')){
$error = array('error' => $this->upload->display_errors());
echo "<pre>";
print_r($error);
exit();
} else {
$fdata = $this->upload->data();
$data['file2'] = 'upload/images' . $fdata['file_name'];
}
$data['name'] = $this->input->post('dname', TRUE);
$data['email'] = $this->input->post('demail', TRUE);
$data['mobile'] = $this->input->post('dmobile', TRUE);
$data['mobile'] = $this->input->post('daddress', TRUE);
$result = $this->insert_model->insert($data);
$sdata = array();
$sdata['message'] = "Well done!</strong> You successfully add the
Product Details.";
$this->session->set_userdata($sdata);
redirect('super_admin/add_product', 'refresh');
}
You should make a method for upload, so you can use it more times.
/**
* Upload a file.
*
* #param $field
* #param $upload_path
* #param string $allowed_types
* #return bool | file_name
*/
public function do_upload($field, $upload_path, $allowed_types = 'jpg|png|gif')
{
$config['upload_path'] = $upload_path;
$config['allowed_types'] = $allowed_types;
$config['max_size'] = 500;
$config['max_width'] = 1024;
$config['max_height'] = 1024;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($field))
{
$this->upload = null; // Unload library
return FALSE;
}
else
{
$data = $this->upload->data();
$this->upload = null; // Unload library
return $data["file_name"];
}
}
Now you can use it in image().
Example
public function image()
{
$data = array();
// For 1st directory
if ($data['image'] = $this->do_upload('your_filed_name', 'upload/')) {
// Statements
// $data['image'] = 'upload/' . $data['image']
} else {
$data['errors'] = array('error' => $this->upload->display_errors());
}
// For 2st directory
if ($data['image'] = $this->do_upload('your_filed_name', 'upload/images/')) {
// Statements
// $data['image2'] = 'upload/images/' . $data['image']
} else {
$data['errors'] = array('error' => $this->upload->display_errors());
}
// Your rest of logic
}
Try this
public function image()
{
$data = array();
$error = array();
$config1=array(
'upload_path'=>'upload/',
'allowed_types'=>'jpg|jpeg|png|bmp',
'max_size'=>0,
'filename'=>url_title($this->input->post('file'))
);
$this->load->library('upload',$config1,'file1'); // Create custom object for file 1 upload
if($this->file1->do_upload('file')){
$error = array('error' => $this->file1->display_errors());
echo "<pre>";
print_r($error);
exit();
}else {
$fdata = $this->file1->data();
$data['image'] = 'upload/' . $fdata['file_name'];
}
$config2=array(
'upload_path'=>'upload/images/',
'allowed_types'=>'jpg|jpeg|png|bmp',
'max_size'=>0,
'filename'=>url_title($this->input->post('file'))
);
$this->load->library('upload', $config2, 'file2'); // Create custom object for file 2 upload
$this->file2->initialize($config2);
if (!$this->file2->do_upload('file')){
$error = array('error' => $this->file2->display_errors());
echo "<pre>";
print_r($error);
exit();
} else {
$fdata = $this->file2->data();
$data['file2'] = 'upload/images' . $fdata['file_name'];
}
$data['name'] = $this->input->post('dname', TRUE);
$data['email'] = $this->input->post('demail', TRUE);
$data['mobile'] = $this->input->post('dmobile', TRUE);
$data['mobile'] = $this->input->post('daddress', TRUE);
$result = $this->insert_model->insert($data);
$sdata = array();
$sdata['message'] = "Well done!</strong> You successfully add the
Product Details.";
$this->session->set_userdata($sdata);
redirect('super_admin/add_product', 'refresh');
}
My problem resolved with following code:
public function image()
{
$config['upload_path'] = './upload/images';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 0;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')){
} else {
$fdata = $this->upload->data();
$data['file2'] = 'upload/images' . $fdata['file_name'];
}
$config2=array(
'upload_path'=>'upload/',
'allowed_types'=>'jpg|jpeg|png|bmp',
'max_size'=>0,
);
$this->upload->initialize($config2);
if($this->upload->do_upload('userfile')){
$data = array(
'name' =>$this->input->post('name'),
'email' =>$this->input->post('email'),
'phone' =>$this->input->post('phone'),
'title' =>$this->input->post('someField'),
'image'=>$this->upload->file_name,
);
//Transfering data to Model
$this->insert_model->add($data);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
Related
i want to upload several image with different input and different field name for each image. i actually try to separate it in two different method like this
public function tambahketua(){
if(isset($_POST["reg"]))
{
$config['upload_path'] = './asset/img/foto/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|xml|docx|GIF|JPG|PNG|JPEG|PDF|DOC|XML|DOCX|xls|xlsx';
$config['max_size'] = 200048;
$config['file_name'] = $this->input->post("namaketua");
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('attachment'))//ini name di input choose file
{
}
else
{
$datas = $this->upload->data();
$edit['image_library'] = 'gd2';
$edit['source_image'] = './asset/img/foto/'.$datas['file_name'];
$edit['create_thumb'] = TRUE;
$edit['maintain_ratio'] = TRUE;
$edit['height'] = 600;
$this->load->library('image_lib', $edit);
$this->image_lib->resize();
$edit_file = explode('.', $datas['file_name']);
$data['foto'] = $edit_file[0].'_thumb.'.$edit_file[1];
unlink($config['upload_path'].$datas['file_name']);
}
$a = $this->miniatur_model->insertPeserta($data);
if($a){
$this->tambahanggota1();
}
else{
echo "failed";
}
}
$this->load->view('pendaftaran');
}
public function tambahanggota1(){
if(isset($_POST["reg"]))
{
$config['upload_path'] = './asset/img/foto/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|xml|docx|GIF|JPG|PNG|JPEG|PDF|DOC|XML|DOCX|xls|xlsx';
$config['max_size'] = 200048;
$config['file_name'] = $this->input->post("namaanggota1");
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('fotoktmanggota1'))//ini name di input choose file
{
}
else
{
$datas = $this->upload->data();
$edit['image_library'] = 'gd2';
$edit['source_image'] = './asset/img/foto/'.$datas['file_name'];
$edit['create_thumb'] = TRUE;
$edit['maintain_ratio'] = TRUE;
$edit['height'] = 600;
$this->load->library('image_lib', $edit);
$this->image_lib->resize();
$edit_file = explode('.', $datas['file_name']);
$data['foto'] = $edit_file[0].'_thumb.'.$edit_file[1];
unlink($config['upload_path'].$datas['file_name']);
}
$a = $this->miniatur_model->insertPeserta($data);
if($a){
echo "success";
}
else{
echo "failed";
}
}
$this->load->view('pendaftaran');
}
and so far i could only write both of the image name into my database, but only the first one uploaded into my folder.
and this is my view
<input type="file" id="attachment" name="attachment">
<input type="file" id="fotoktmanggota1" name="fotoktmanggota1">
and for some reason i cant change the name of my files into array like name="attachment[]"
I have minimized your extra code. Try this and do your own magic if I missed something.
function tambahketua() {
if (isset($_POST["reg"])) {
$config['upload_path'] = './asset/img/foto/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|xml|docx|GIF|JPG|PNG|JPEG|PDF|DOC|XML|DOCX|xls|xlsx';
$config['max_size'] = 200048;
$this->upload->initialize($config);
if (!$this->upload->do_upload('attachment')) {
$error = array('error' => $this->upload->display_errors());
// var_dump($error);
} else {
$fileData = $this->upload->data();
$data['foto'] = $fileData['file_name'];
$this->doResize($fileData['file_name']);
}
$insertedFirstImage = $this->miniatur_model->insertPeserta($data);
if ($insertedFirstImage) {
// Upload Second Image on Success
if (!$this->upload->do_upload('fotoktmanggota1')) {
$error = array('error' => $this->upload->display_errors());
} else {
$fileData = $this->upload->data();
$data['foto'] = $fileData['file_name'];
$this->doResize($fileData['file_name']);
}
$insertedSecondImage = $this->miniatur_model->insertPeserta($data);
/*---------------------------------------*/
} else{
echo "Image insertion Failed in database";
}
}
$this->load->view('pendaftaran');
}
function doResize($filename) {
$sourcePath = './asset/img/foto/' . $filename;
$targetPath = './asset/img/foto/thumb/thumb_' . $filename;
$config_manip = array(
'image_library' => 'gd2',
'source_image' => $sourcePath,
'new_image' => $targetPath,
'maintain_ratio' => true,
'width' => 150,
'height' => 150
);
$this->image_lib->initialize($config_manip);
$this->load->library('image_lib', $config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
exit;
}
// clear //
// $this->image_lib->clear();
}
I've a file uploader. I do the overwrite through the data. It makes me upload these data:
- Pict1.jpg
- Pict12.jpg
- Pict13.jpg
But when I tried to return it, its only showing pict1.jpg. Here the code
Controller:
function send(){
$mariupload = $this->upload_gambar($_FILES['gambar']);
if ($mariupload === FALSE) {
$upload = false;
}
if($upload = false){
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
} else {
$dataupload = $mariupload;
echo $dataupload;
}
private function upload_gambar($files){
//config buat upload gambar
$config['upload_path'] = 'path to upload';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '1024';
$config['overwrite'] = '0';
$this->load->library('upload', $config);
$gambar = array();
if (is_array($files['name']) || is_object($files['name'])){
foreach ($files['name'] as $key => $gambar) {
$_FILES['gambar[]']['name']= $files['name'][$key];
$_FILES['gambar[]']['type']= $files['type'][$key];
$_FILES['gambar[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['gambar[]']['error']= $files['error'][$key];
$_FILES['gambar[]']['size']= $files['size'][$key];
$fileName = $gambar;
$images[] = $fileName;
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if ($this->upload->do_upload('gambar[]')) {
$dataupload = $this->upload->data('file_name');
return $dataupload.'<br>';
} else {
$mariupload = false;
}
}
}
}
When i try to echo $dataupload in upload_gambar function, it works as an array. But its returning as a single data to send() function. Any idea?
Because you are sending just single file
$mariupload = $this->upload_gambar($_FILES['gambar']);
change this to
$mariupload = $this->upload_gambar($_FILES);
then in your upload_gambar handle it as foreach
You have a return inside the loop. A return will interrupt the loop as the function will not continue to be executed. Try to feed up an array instead.
Replace
return $dataupload.'<br>';
With
$return[] = $dataupload;
And at the end of the function append:
return $return;
I finally found the solution. Thanks to Jovi Wang on Facebook (https://www.facebook.com/jovi.wang.96?fref=ufi) . This is the clean code:
function send(){
$try = $this->upload_multiple($_FILES['gambar']);
if(!$try = false){
$anu= $this->upload_multiple($_FILES['gambar']);
foreach($anu as $key => $anu2){
echo $anu2.'<br>';
}
}
public function upload_multiple($files)
{
// echo '<pre>';
// print_r($files);
// echo '</pre>';
$config['upload_path'] = 'path to upload';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024;
$config['overwrite'] = 0;
$config['encrypt_name'] = TRUE;
$this->load->library('upload');
$this->upload->initialize($config);
$data = array();
foreach($files['name'] as $key => $value)
{
if ( ! empty($files['name'][$key]))
{
$_FILES['gambar_single']['name'] = $files['name'][$key];
$_FILES['gambar_single']['name'] = $files['name'][$key];
$_FILES['gambar_single']['type'] = $files['type'][$key];
$_FILES['gambar_single']['tmp_name'] = $files['tmp_name'][$key];
$_FILES['gambar_single']['error'] = $files['error'][$key];
$_FILES['gambar_single']['size'] = $files['size'][$key];
if ($this->upload->do_upload('gambar_single'))
{
$data[] = $this->upload->data('file_name');
}
else
{
$data[] = $this->upload->display_errors();
}
}
else
{
$data[] = 'empty upload';
}
}
return $data;
}
<?php
public function videoupld()
{
$this->load->helper('string');
$config['upload_path'] = 'assets/upload/video'; # check path is correct
$config['max_size'] = '102400000';
$config['allowed_types'] = 'mp4'; # add video extenstion on here
$config['overwrite'] = FALSE;
$config['remove_spaces'] = TRUE;
$video_name =$_FILES['video_image']['name'];`
$config['file_name'] = $video_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('video_image'))
{
echo 'fail';
return;
//redirect('Admin/video_upload');
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
$url = 'assets/upload/video'.$video_name;
$this->Admin_model->videoupld($url);
redirect('Admin/video_upload');
}
}
?>
model
public function videoupld($url)
{
$title = $this->input->post('video_image');
//$details = $this->input->post('details');
//$type = $this->input->post('gallery');
$data = array(
'title' => $title,
'url' => $url,
//'category' => $type`
);
$this->db->insert('videoss', $data);
}
$uploaded = $this -> upload -> do_upload('video_image');
//here you will receive the object that you uploaded
// you will test if the file exist if yes the variable $file will recieve the full path
if ($uploaded) {
if ($data['file_ppt'] != '') {
$file = 'uploads/ppt/' . $data['file_ppt']; //full path
if (file_exists($file)) {
unlink($file);
}
}
}
//if file uploaded
//$save['file_ppt'] will have the name of the file uploaded
if ($uploaded) {
$file_ppt = $this -> upload -> data();
$save['file_ppt'] = $file_ppt['file_name'];
}
$uploaded = $this -> upload -> do_upload('video_image');
if ($uploaded) {
if ($data['file_ppt'] != '') {
$file = 'uploads/ppt/' . $data['file_ppt'];
if (file_exists($file)) {
unlink($file);
}
}
}
if ($uploaded) {
$file_ppt = $this -> upload -> data();
$save['file_ppt'] = $file_ppt['file_name'];
}
$this->db->insert('videoss', $save);
put this in the view :
and in controller : $names ="";
$name_array = array();
if(isset($_FILES['file_ppt'])){
$count = count($_FILES['file_ppt']['size']);
}else{
$count=0;
}
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++) {
$_FILES['file_ppt']['name']=md5(time())."".$value['name'][$s];
$_FILES['file_ppt']['type'] = $value['type'][$s];
$_FILES['file_ppt']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['file_ppt']['error'] = $value['error'][$s];
$_FILES['file_ppt']['size'] = $value['size'][$s];
// $config['allowed_types'] = 'gif|jpg|png';
$config['upload_path'] = 'uploads/messages';
$config['allowed_types'] = '*';
$config['max_size'] = '200000';
$this->load->library('upload', $config);
$uploaded = $this->upload->do_upload('file_ppt');
$data = $this->upload->data();
$names = $names.','.$_FILES['file_ppt']['name'];
}
if ($uploaded) {
// $file_ppt = $this -> upload -> data();
$save['file_ppt'] = $names;
// print_r('file ppt'.$file_ppt['file_name']);
}else {
echo $this->upload->display_errors();
}
In my controller I have the following functions that upload an image to a local directory which works fine. I now want to store in the db. I just need to figure out where to put the code I already have and think is correct.
I need to insert this:
$this->location->store_file_path($file);
into either before or after the pic is uploaded in local directory. Where should it go?
Controller:
public function image() {
//type must either be type=logo or type=profile_picture
if (isset($_FILES['file']) && isset($_POST['type'])) {
//Codeigniter upload
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['encrypt_name'] = TRUE;
$config['max_size'] = 5120;
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->upload->initialize($config);
if (!$this->upload->do_upload('file')) {
$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 ($data) {
$status = "success";
$data['url'] = $config['upload_path'] . $data['file_name'];
$msg = $data;
} else {
unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
} else {
$status = "error";
$msg = "Please select a file to upload";
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
Here is my model function:
public function store_file_path($file)
{
$this->db->insert('TACTIFY_locationcards', 'name'=>$file);
}
change the following line in controler
$status = "success";
+ $file = $config['upload_path'] . $data['file_name'];
+ $this->location->store_file_path($file);
$msg = $file;
change the model
public function store_file_path($file)
{
+ $this->db->set('name', $file);
+ $this->db->insert('TACTIFY_locationcards');
- $this->db->insert('TACTIFY_locationcards', 'name'=>$file);
}
I suggest you only write to a database once all verification has been done and the data has been written to the file.
If I read your code correctly success is at the point:
if ($data) {
$status = "success";
$data['url'] = $config['upload_path'] . $data['file_name'];
$msg = $data;
I would put the line here:
if ($data) {
$status = "success";
$data['url'] = $config['upload_path'] . $data['file_name'];
$msg = $data;
$this->location->store_file_path($file);
I need some help. I want to upload two different files in two different directory by using codeigniter. I wrote the following code in my controller. but it will upload only the first image.
public function save_product() {
$data = array();
$error = array();
$config1['upload_path'] = './manager/images/products/';
$config1['allowed_types'] = 'gif|jpeg|png|jpg';
$config1['max_size'] = '3000000';
$config1['max_width'] = '1024';
$config1['max_height'] = '768';
$this->load->library('upload', $config1);
$config2['upload_path'] = './manager/images/products/large/';
$config2['allowed_types'] = 'gif|jpeg|png|jpg';
$config2['max_size'] = '3000000';
$config2['max_width'] = '1024';
$config2['max_height'] = '768';
$this->load->library('upload', $config2);
if ((!$this->upload->do_upload('product_small_image')) && (!$this->upload->do_upload('product_large_image'))){
$error = array('error' => $this->upload->display_errors());
echo "<pre>";
print_r($error);
exit();
}
else {
$fdata = $this->upload->data();
$data['product_small_image'] = 'manager/images/products/' . $fdata['file_name'];
$data['product_large_image'] = 'manager/images/products/large/' . $fdata['file_name'];
$data['product_id'] = $this->input->post('product_id', TRUE);
$data['product_name'] = $this->input->post('product_name', TRUE);
$data['category'] = $this->input->post('category', TRUE);
$result = $this->super_admin_model->save_product_detail($data);
$sdata = array();
$sdata['message'] = "Well done!</strong> You successfully add the Product Details.";
$this->session->set_userdata($sdata);
redirect('super_admin/add_product', 'refresh');
}
}
First, loading the library again with $config2 won't work because the library is already loaded once and $config1 will stay loaded. To load a new config use $this->upload->initialize($config2);
Second, loading $config2 will overwrite the previous config. You should re-arrange your code. Otherwise both uploads will only use the latest config ($config2). Example:
Load library with $config1
Process do_upload('product_small_image') and collect result
Load $confg2 using initialize()
Process do_upload('product_large_image') and collect result
Process results (save to db if success or display error if one of the uploads failed)
Here is the total code what i wrote to upload multiple image in different directory successfully. and thanks to #Samutz again.
public function save_product() {
$data = array();
$error = array();
$config1['upload_path'] = './manager/images/products/';
$config1['allowed_types'] = 'gif|jpeg|png|jpg';
$config1['max_size'] = '3000000';
$config1['max_width'] = '1024';
$config1['max_height'] = '768';
$this->load->library('upload', $config1);
if (!$this->upload->do_upload('product_small_image')){
$error = array('error' => $this->upload->display_errors());
echo "<pre>";
print_r($error);
exit();
}
else {
$fdata = $this->upload->data();
$data['product_small_image'] = 'manager/images/products/' . $fdata['file_name'];
}
$config2['upload_path'] = './manager/images/products/large/';
$config2['allowed_types'] = 'gif|jpeg|png|jpg';
$config2['max_size'] = '3000000';
$config2['max_width'] = '1024';
$config2['max_height'] = '768';
$this->upload->initialize($config2);
if (!$this->upload->do_upload('product_large_image')){
$error = array('error' => $this->upload->display_errors());
echo "<pre>";
print_r($error);
exit();
}
else {
$fdata = $this->upload->data();
$data['product_large_image'] = 'manager/images/products/large/' . $fdata['file_name'];
}
$data['product_id'] = $this->input->post('product_id', TRUE);
$data['product_name'] = $this->input->post('product_name', TRUE);
$data['category'] = $this->input->post('category', TRUE);
$result = $this->super_admin_model->save_product_detail($data);
$sdata = array();
$sdata['message'] = "Well done!</strong> You successfully add the Product Details.";
$this->session->set_userdata($sdata);
redirect('super_admin/add_product', 'refresh');
}