I have codeigniter application, Now i need to Upload excel using the codigniter.
How to do that. I follow some Online tutorials, but there are not complete one. Specially there are no what is the library they use.
if(isset($_POST['Submit']))
{
$mimes = array('application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.oasis.opendocument.spreadsheet','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
if(in_array($_FILES["file"]["type"],$mimes))
{
$uploadFilePath = 'uploads/'.basename($_FILES['file']['name']);
$filename = pathinfo($uploadFilePath);
$f = array("name"=>$filename['filename']);
foreach ($f as $k)
{
$policy = $k;
}
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath);
$Reader = new SpreadsheetReader($uploadFilePath);
$totalSheet = count($Reader->sheets());
//echo "You have total ".$totalSheet." sheets".
/* For Loop for all sheets */
for($i=0;$i<$totalSheet;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row)
{
$treeno ++;
$policyno = isset($Row[0]) ? $Row[0] : '';
$act_treeno = isset($Row[1]) ? $Row[1] : '';
$dbh = isset($Row[2]) ? $Row[2] : '';
$height = isset($Row[3]) ? $Row[3] : '';
$pno = substr($policyno, -6);
$treeno = $pno.'_'.$act_treeno.'_T';
$query = "insert into tbl_trees(policyno,actual_treeno,dbh,height,treeno) values('".$policyno."','".$act_treeno."','".$dbh."','".$height."','".$treeno."')";
echo '</br>';
$mysqli->query($query);
this is work, but i have not idea to use this method in codeigniter.
First think you need upload that file then try open and prepare data for insert-
$fileName = $_FILES['file']['name'];
$uploadData = array();
if (!empty($fileName)) {
$config['upload_path'] = './your location/';
$config['allowed_types'] = 'txt|csv|xls|xlsx';
$config['max_size'] = 2048;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('file')) {
json_error("File Upload Error", $this->upload->display_errors(), 400);
} else {
$uploadData = array('upload_data' => $this->upload->data());
}
}//if
prepare data for insert-
if (!empty($uploadData)) {
$fileName = $uploadData['upload_data']['file_name'];
$data = array(); //empty array;
$fileInfo = fopen(base_url() . 'your file location/' . $fileName, "r");
$i = 0;
while (!feof($fileInfo)) {
$colInfo = fgets($fileInfo); //fgets means read file in line by line.
//prefer data to save
$data[$i]['your_column'] = $colInfo;
$i++;
}//while
fclose($fileInfo);
}
insert batch data-
$this->db->insert_batch('dbtable', $data);
Related
The following php pdf to image code with imagick in codeigniter framework has a problem in the controller, imagick cannot read my file pdf.
error:
[codeigniter] An uncaught Exception was encountered Type: ImagickException Message: Failed to read the file in Codeigniter.
controller:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Files_upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('files');
}
function index(){
$data['gallery'] = $this->db->query("select * from gallery order by id desc limit 10")->result();
$data = array();
if($this->input->post('submitForm') && !empty($_FILES['upload_Files']['name'])){
$filesCount = count($_FILES['upload_Files']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['upload_File']['name'] = $_FILES['upload_Files']['name'][$i];
$_FILES['upload_File']['type'] = $_FILES['upload_Files']['type'][$i];
$_FILES['upload_File']['tmp_name'] = $_FILES['upload_Files']['tmp_name'][$i];
$_FILES['upload_File']['error'] = $_FILES['upload_Files']['error'][$i];
$_FILES['upload_File']['size'] = $_FILES['upload_Files']['size'][$i];
$uploadPath = 'uploads/files/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|mp4|avi';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('upload_File')){
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
}
}
if(!empty($uploadData)){
//Insert file information into the database
$insert = $this->files->insert($uploadData);
$statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('statusMsg',$statusMsg);
}
$this->load->helper('url');
$ImageName = $_FILES['upload_File']['name'];
$loc = base_url().$uploadPath.$ImageName;
echo $ImageName;
echo $loc;
$im = new imagick($loc);
$noOfPagesInPDF = $im->getNumberImages();
if ($noOfPagesInPDF) {
for ($i = 0; $i < 1; $i++) {
$url = $loc.'['.$i.']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->setImageCompressionQuality(80);
$image->writeImage("uploads/files/img/".($i+1).'-'.$ImageName.'.jpg');
}
}
for($i = 0; $i<1;$i++) {
$img = "uploads/files/img/".($i+1).'-'.$ImageName.'.jpg';
$display .= "<img src='$img' title='Page-$i' /><br>";
}
$message = "PDF converted to JPEG sucessfully!!";
}
//Get files data from database
$data['gallery'] = $this->files->getRows();
//Pass the files data to view
$this->load->view('files_upload/index', $data);
}
}
Solved
Is Correct Code
$ImageName= $fileData['file_name'];
$loc = realpath(APPPATH.'../uploads/files/').'/'.$ImageName;
Or you can just do
$loc = $fileData['full_path'];
This will work (tested):
//$data['gallery'] = $this->db->query("select * from gallery order by id desc limit 10")->result(); // same at bottom??
$message = '';
$display = '';
if ($this->input->post('submitForm') && !empty($_FILES['userfile']['name'])) {
$uploadPath = FCPATH . 'uploads/files/';
if (!is_dir($uploadPath) && mkdir($uploadPath, DIR_WRITE_MODE, true) == false) {
show_error('Folder cannot be made!');
}
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|mp4|avi';
$this->load->library('upload', $config);
// change input field to <input type="file" name="userfile">
if (!$this->upload->do_upload()) {
$this->session->set_flashdata('statusMsg', $this->upload->display_errors());
} else {
$fileData = $this->upload->data();
$uploadData['file_name'] = $fileData['file_name'];
$uploadData['created'] = date("Y-m-d H:i:s");
$uploadData['modified'] = date("Y-m-d H:i:s");
$insert = $this->files->insert($uploadData);
$insert = true;
if (!$insert) {
#unlink($fileData['full_path']); // remove orphan
$this->session->set_flashdata('statusMsg', 'Database error. Please try again');
} else {
$this->session->set_flashdata('statusMsg', 'Files uploaded successfully.');
if ($fileData['file_ext'] == '.pdf') {
try {
$newPath = $uploadPath . 'img/';
if (!is_dir($newPath) && mkdir($newPath, DIR_WRITE_MODE, true) == false) {
throw new Exception('Folder cannot be made!');
}
$ImageName = $fileData['raw_name'];
$loc = $fileData['full_path'];
$im = new Imagick($loc);
$pdfPageCount = $im->getNumberImages();
if ($pdfPageCount > 0) {
for ($i = 0; $i < $pdfPageCount; $i++) {
$url = $loc . '[' . $i . ']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->setImageCompressionQuality(80);
$image->writeImage($newPath . ($i + 1) . '-' . $ImageName . '.jpg');
$img = base_url("uploads/files/img/" . ($i + 1) . '-' . $ImageName . '.jpg');
$display .= "<img src='$img' title='Page-$i' /><br>";
}
echo $display; // debugging
$this->session->set_flashdata('statusMsg', "PDF converted to JPEG(s) sucessfully!");
}
} catch (Exception $e) {
#unlink($fileData['full_path']); // remove orphan
$this->session->set_flashdata('statusMsg', $e->getMessage());
}
} else {
echo 'not a pdf'; // debugging only
}
}
}
}
//Get files data from database
$data['gallery'] = $this->files->getRows();
//Pass the files data to view
$this->load->view('files_upload/index', $data);
Please note the input file field should now look like this:
<input type="file" name="userfile" />
You will also have to revise:
$this->files->insert($uploadData) function
I am trying to upload image to database MySQL. But I have a problem, when I am trying to upload one image, the image inserted twice.
For example:
I have "A.jpg" if I try to upload it
the inserted data will be like "A.jpg,A.jpg"
What I want in database "A.jpg"
and if I try to upload multiple images like "A.jpg,B.jpg and C.jpg"
the inserted data will be like "B.jpg,B.jpg,C.jpg,C.jpg"
What I want in database "A.jpg,B.jpg,C.jpg"
I've tried to search on google but no results, anyone can help me to resolve this problem ? Thanks
Here is my code :
include('koneksi.php');
date_default_timezone_set('Asia/Jakarta');
$id_user = $_POST['id_user'];
$caption = $_POST['caption'];
$files = [];
foreach($_FILES['files']['name'] as $i => $name) {
$name = $_FILES['files']['name'][$i];
$size = $_FILES['files']['size'][$i];
$type = $_FILES['files']['type'][$i];
$tmp = $_FILES['files']['tmp_name'][$i];
$explode = explode('.', $name);
$ext = end($explode);
$updatdName = $explode[0] . time() .'.'. $ext;
$path = 'gallery/';
$path = $path . basename( $updatdName );
if(empty($_FILES['files']['tmp_name'][$i])) {
$errors[] = 'Please choose at least 1 file to be uploaded.';
}else {
$allowed = array('jpg','JPG','jpeg','JPEG','gif','GIF','bmp','BMP','png','PNG');
$max_file_size = 1024*1024*2;; // 2MB
if(in_array($ext, $allowed) === false) {
$errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
}
if($size > $max_file_size) {
$errors[] = 'The file <b>'.$name.'</b> size is too hight.';
}
}
if(empty($errors)) {
// if there is no error then set values
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$errors = array();
if(!file_exists('gallery')) {
mkdir('gallery', 0777);
}
if(move_uploaded_file($tmp, $path)) {
echo '<script>window.history.back()</script>';
}else {
echo 'Something went wrong while uploading
<b>'.$name.'</b>';
}
}else {
foreach($errors as $error) {
echo '<p>'.$error.'<p>';
}
}
}
if(!empty($files)) {
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$names = implode(',', $files['file_name']);
$sizes = implode(',', $files['size']);
$types = implode(',', $files['type']);
$sql="INSERT into status VALUES(NULL, '$id_user', '$names','$caption','foto',NOW()); ";
mysqli_query($koneksi, $sql);
}
You're setting $files['file_name'][] in the while loop and also right before inserting into the DB. You just need to remove 2nd call to $files['file_name'][] = $updatdName;
Here is a simplified version of what you're doing.
<?php
$_FILES[] = ['name' => 'A'];
$_FILES[] = ['name' => 'B'];
$_FILES[] = ['name' => 'C'];
$files = [];
foreach ($_FILES as $file) {
$updatdName = $file['name'];
// You're setting it here
$files['file_name'][] = $updatdName;
}
if (!empty($files)) {
// And also here.
$files['file_name'][] = $updatdName;
$names = implode(',', $files['file_name']);
echo $names;
}
I try to upload data with different type of extension with codeigniter but I have constraints file it does not go into the folder that I go. i try to make some config according to what i need, please help ..
function add_module_external(){
$id_module = '9090909';
$file_data = array();
$file_data2 = array();
$image_data = array();
$config_video = array();
$config_image["file_name"] = $id_module;
$config_image["upload_path"] = "./assets/file/image-module/";
$config_image["overwrite"] = TRUE;
$config_image["allowed_types"] = "gif|jpg|png|";
$this->load->library('upload', $config_image);
$this->upload->initialize($config_image);
$upload_background = $this->upload->do_upload('other_image');
if($upload_background){
$image_data = $this->upload->data();
$image = $image_data['file_name'];
}else{
$image = $this->input->post('background');
}
// pdf and ppt upload
$config_file['file_name'] = $id_module;
$config_file['upload_path'] = '/assets/file/materi-module/';
$config_file['overwrite'] = TRUE;
$config_file['allowed_types'] = 'pdf';
$this->load->library('upload', $config_file);
$this->upload->initialize($config_file);
$upload_pdf = $this->upload->do_upload('pdf_data');
if($upload_pdf){
$file_data = $this->upload->data();
$content = $file_data["file_name"];
}else if($upload_ppt){
$file_data2 = $this->upload->data();
$content = $file_data2["file_name"];
}else if($upload_video){
$config_video = $this->upload->data();
$content = $config_video["file_name"];
}else{
$content = $this->input->post("text_data");
}
$query = $this->my_module->new_module($image, $id_module, $content);
redirect($this->agent->referrer());
}
I have a submit file code that uploads an Excel file to my server and then uses it through the function.
When doing so:
if ($this->upload->do_upload()){
$data = array('upload_data' => $this->upload->data());
$filename = $data['raw_name'];
$fullfilename = $data['orig_name'];
$inputFileName = FCPATH."files/automation/1/$filename.xlsx";
$inputFileNameNew = FCPATH."files/automation/1/$filename-new.xlsx";
It gives me this output:
Error loading file ".xlsx": Could not open
/var/www/html/tools/files/automation/1/.xlsx for reading! File does
not exist.
Where I suspect it's because it hasn't found the file because it wasn't uploaded yet. Could be?
if you want to upload a file in diferents folders by user or whatever you need to do this
public function upload_f(){
$config['upload_path'] = FCPATH . '/files/automation/' . $id . '/';
$config['allowed_types'] = 'xls|xlsx';
$this->load->library('upload', $config);
if( ! $this->upload->do_upload()){
$this->session->set_flashdata('upload-no', $this->upload->display_errors());
}
else{
$this->_read_file(FCPATH . '/files/automation/' . $id . '/' . $this->upload->file_name);
}
}
private funtion _read_file( $file ){
$this->load->library('excel');
$this->load->library('table');
$file = str_replace('//', '/', $file);
$objPHPExcel = PHPExcel_IOFactory::load($file);
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
$lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
if ($row == 1) {
$header[$row][$column] = $data_value;
}
else{
$arr_data[$row][$column] = $data_value;
}
}
$this->table->set_heading('ID', 'value1', 'value2');
for($i = 2; $i <= $lastRow; $i++){
$_table= array($i, $arr_data[$i]['A'], $arr_data[$i]['B']);
$this->table->add_row($_table);
}
echo $this->table->generate();
}
I'm using class.upload.php for images. Resizing works correctly with name and extension into the folder, but i have a problem storing the name into mysql database. There's no file extension (.jpg, .gif etc)... why? how can i resolve the problem?
Thanks
/* ========== SCRIPT UPLOAD MULTI IMAGES ========== */
include('class.upload.php');
$dir_dest="../../images/gallery/";
$files = array();
foreach ($_FILES['fleImage'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new Upload($file);
if ($handle->uploaded) {
$mainame = $handle->file_dst_name;
$db_name = str_replace(" ","_",$mainame);
$image1 = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image1);
$extension = end($parts);
$result_big = str_replace("." . $extension,"",$image1);
$handle->file_new_name_body = $result_big;
$handle->image_resize = true;
$handle->image_x = 460;
$handle->image_ratio_y = true;
// $handle->image_y = 400;
$handle->Process($dir_dest);
//Thumbnail
$db_name = str_replace(" ","_",$mainame);
$image1 = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image1);
$extension = end($parts);
$result_small = str_replace("." . $extension,"",$image1);
$handle->file_new_name_body = $result_small;
$handle->image_resize = true;
$handle->image_x = 180;
$handle->image_ratio_y = true;
// $handle->image_y = 120;
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
header("Location: index.php"); //echo 'image resized';
$handle->clean();
$query_img="INSERT into tbl_images (file_name, pd_image, pd_thumbnail) VALUES('$nome','$result_big', '$result_small')";
$result2 = dbQuery($query_img);
} else {
echo 'error : ' . $handle->error;
}
}
}
// END SCRIPT UPLOAD MULTI IMAGES
header("Location: index.php");
}
You are removing the extension with this code
$result_big = str_replace("." . $extension,"",$image1);
I dont know why you do that. anyway you can add it back by adding following line after the $handle->file_new_name_body = $result_big;
$handle->file_new_name_ext = $extension;
You have replaced the extention with empty string here using str_replace
$result_small = str_replace("." . $extension,"",$image1);
and here
$result_big = str_replace("." . $extension,"",$image1);
update below lines just add .$extension at the end
$handle->file_new_name_body = $result_big.$extension;
and
$handle->file_new_name_body = $result_small.$extension;
just change query like this
$query_img="INSERT into tbl_images (
file_name,
pd_image,
pd_thumbnail
) VALUES (
'$nome',
'{$result_big}.{$extension}',
'{$result_small}.{$extension}')";
I will suggest you to have same filename for pd_image and pd_thumbnail, just prefix thumb with thumb_ that will make your life easier in front end.
this way you can access any image thumbnail just by prefixing it with thumb_ with pd_image and you don't have to store pd_thumbnail in database.