Codeiginter - do_upload "File not selected" - codeigniter

I'm trying to upload an image from a WYSIWYG textarea (TinyMCE), but it's not working, it gives me the error "File not selected".
I'm using multipart form, is it conflicting with other "input file" ?
Thanks.
Here is the code i'm using.
View (.twig)
{{ form_open_multipart() }}
...
<div class="form-group">
<label class="col-sm-2 control-label">Texto</label>
<div class="col-sm-10">
{{ form_textarea('text',set_value('text') ? set_value('text') : post.text|raw,'class="form-control editor"') }}
<input name="image" type="file" id="upload_img_wysiwyg" class="hidden" onchange="">
</div>
</div>
{{ form_close() }}
Controller
public function upload_image_tinymce() {
//Check whether user upload picture
if (!empty($_FILES['image']['name'])) {
$config['upload_path'] = ADDONPATH.'themes/escolamagica/img/escolamagica-blog/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['image']['name'];
$config['overwrite'] = TRUE;
$config['max_size'] = '10240';
$config['max_width'] = '10000';
$config['max_height'] = '10000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image')) {
$picture = str_replace('\\', '/', base_url().'img/escolamagica-blog/'.$_FILES['image']['name']);
} else {
echo 'CONFIG';
var_dump($config);
echo 'IMAGE';
var_dump($_FILES);
echo 'ERROR';
$error = array('error' => $this->upload->display_errors());
var_dump($error);
die;
$picture = '';
}
} else {
$picture = '';
}
return $picture;
}
Javascript
function initImageUpload(editor) {
// create input and insert in the DOM
var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
$(editor.getElement()).parent().append(inp);
// add the image upload button to the editor toolbar
editor.addButton('imageupload', {
text: '',
icon: 'image',
onclick: function(e) { // when toolbar button is clicked, open file select modal
inp.trigger('click');
}
});
// when a file is selected, upload it to the server
inp.on("change", function(e){
uploadFile($(this), editor);
});
}
function uploadFile(inp, editor) {
var input = inp.get(0);
var data = new FormData();
data.append('image[file]', input.files[0]);
$.ajax({
url: BASE_URL + 'admin/blog/upload_image_tinymce',
type: 'POST',
data: data,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) {
console.log(data);
editor.insertContent('<img class="content-img" src="' + data.url + '"/>');
},
error: function(jqXHR, textStatus, errorThrown) {
if(jqXHR.responseText) {
errors = JSON.parse(jqXHR.responseText).errors
alert('Error uploading image: ' + errors.join(", ") + '. Make sure the file is an image and has extension jpg/jpeg/png.');
}
}
});
}
tinymce.init({
language: "pt_PT",
language_url: BASE_URL + "/admin/js/pt_PT.js",
selector: ".editor",
height: 600,
plugins: [
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking save table contextmenu directionality",
"emoticons template paste textcolor colorpicker textpattern"
],
toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link imageupload",
toolbar2: "print preview media | forecolor backcolor emoticons",
image_advtab: !0,
setup: function(editor) {
initImageUpload(editor);
}

You are using a different index for the upload in your form and the tinyMce image upload. Your html form has file input with the name "image". But your MCE ajax file upload has the name "pic". So, in your controller function upload_image_tinymce() replace $_FILES['image'] with $_FILES['pic']
Use this in controller :
public function upload_image_tinymce() {
//Check whether user upload picture
if (!empty($_FILES['pic']['name'])) {
$config['upload_path'] = ADDONPATH.'themes/escolamagica/img/escolamagica-blog/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['pic']['name'];
$config['overwrite'] = TRUE;
$config['max_size'] = '10240';
$config['max_width'] = '10000';
$config['max_height'] = '10000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('pic')) {
$picture = str_replace('\\', '/', base_url().'img/escolamagica-blog/'.$_FILES['pic']['name']);
} else {
echo 'CONFIG';
var_dump($config);
echo 'IMAGE';
var_dump($_FILES);
echo 'ERROR';
$error = array('error' => $this->upload->display_errors());
var_dump($error);
die;
$picture = '';
}
} else {
$picture = '';
}
return $picture;
}

Related

How to export or download csv file using ajax?

I have a problem with my code downloading csv file.
I can get the data but i can't download the csv file.
Here is my ajax code:
// Export
$('#export_csv').click(function(){
var checkbox = $('.checkbox:checked');
if(checkbox.length > 0)
{
var checkbox_value = [];
$(checkbox).each(function(){
checkbox_value.push($(this).val());
});
$.ajax({
url:"csv_action.php",
method:"POST",
data:{action:'export_csv'},
dataType:'json',
success:function(data)
{
$("#select_all").prop('checked', false);
$('#message').html(data);
setTimeout(function(){
$('#message').html('');
}, 5000);
}
});
}
else
{
alert("Please select at least one records");
}
});
Here is my php file code:
The output for this code is the data that i fetch from the database and the data of the student i selected from data table. I tried several methods changing the data type is response and function(success)
// Export CSV
if($_POST["action"] == 'export_csv')
{
$filename = 'reports.csv';
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
for($count = 0; $count < count($_POST["checkbox_value"]); $count++)
{
$object->query = "
SELECT * FROM tbl_student WHERE
s_scholar_stat = ''
";
$object->execute();
$result = $object->get_result();
$content = array();
$title = array("Student ID", "First Name", "Middle Initial", "Last Name", "Date of Birth", "Account Status");
foreach ($result as $rows) {
$row = array();
$row[] = $rows["ss_id"];
$row[] = $rows["sfname"];
$row[] = $rows["smname"];
$row[] = $rows["slname"];
$row[] = $rows["sdbirth"];
$row[] = $rows["s_account_status"];
$content[] = $row;
}
}
$output = fopen('php://output', 'w');
fputcsv($output, $title);
foreach ($content as $con) {
fputcsv($output, $con);
}
fclose($output);
echo '<div class="alert alert-success">Selected Student Data Exported in CSV
Successfully</div>';
}

Codeigniter upload file with dropzone and parameters

Somehow it just doesnt upload the image to the folder. It goes so far as adding to the database (what model is all about) however no upload.
I hope to know what im doing rong. See my code bellow
The
HTML
<div class="dropzone infile dz-clickable" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" id="file" type="file" multiple />
</div>
</div>
JS
var myDropzone = new Dropzone("#my-dropzone", {
url: admin_url+'add_image/material',
files: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function (data) {
this.on("sending",function(file, xhr, formData){
file.token = Math.random().toString(36).substr(2,9);
formData.append("token",file.token);
formData.append("type", file.type);
formData.append("size", file.size);
});
this.on("complete", function (file) {
console.log(file);
});
this.on("successmultiple", function(file, response) {
console.log(file);
});
this.on("errormultiple", function(file, response) {
console.log(file);
});
this.on("removedfile",function(file){
var token = file.token;
$.ajax({
type:"post",
data:{token:token},
url: admin_url+'remove_image',
cache:false,
dataType: 'json',
success: function(res){
}
});
});
},
dictDefaultMessage: "<div class='drag-icon-cph'><i class='material-icons'>touch_app</i></div><h5>Plaats hier bestanden om te uploaden</h5>",
dictRemoveFile : "Bestand verwijderen"
});
PHP (Codeigniter)
public function add_image($type, $rel_id = 0){
if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
$path = getcwd() . '/uploads/';
$tmpFilePath = $_FILES['file']['tmp_name'];
if (!empty($tmpFilePath) && $tmpFilePath != '') {
$path_parts = pathinfo($_FILES["file"]["name"]);
$extension = $path_parts['extension'];
$extension = strtolower($extension);
$allowed_extensions = array(
'jpg',
'jpeg',
'png'
);
if (!in_array($extension, $allowed_extensions)) {
set_alert('warning', 'PHP blocked file extention');
return false;
}
$filename = uniqid(rand(), true).'.'.$extension;
$newFilePath = $path . '/' . $filename;
// Upload the file into the upload dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$CI =& get_instance();
$config = array();
$config['image_library'] = 'gd2';
$config['source_image'] = $newFilePath;
$config['new_image'] = $filename;
$config['maintain_ratio'] = true;
$CI->load->library('image_lib', $config);
$CI->image_lib->initialize($config);
$CI->image_lib->resize();
$CI->image_lib->clear();
$data = array(
'rel_type' => $type,
'rel_id' => $rel_id,
'attachment_key' => $this->input->post('token'),
'file_name' => $filename,
'filetype' => $this->input->post('type'),
'size' => $this->input->post('size'),
'dateadded' => date('Y-m-d H:i:s')
);
$id = $this->back_model->add_image($data);
if($id != ''){
array_push($_SESSION['tmp_image'],$id);
}
unlink($newFilePath);
}
}
}
}
The folder uploads is created and for security i added a empty index.html file.
.htaccess is standard Codeigniter

uploading multiple image in codeigniter using same input

views
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="userfile[]" size="40" multiple/>
<input type="submit" name="submit" value="Upload">
</form>
controller
public function image()
{
$data['error'] = '';
$this->load->model('StackM');
if(isset($_POST['submit']))
{
$data['update_pass_error_msg'] = $this->StackM->add_multiple_image();
}
$this->load->view('stack_view');
}
Model
public function add_multiple_image(){
if((!empty($_FILES['f2']['name'])))
{
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$files = $_FILES;
if ($files['f2']['name'][0] == '' )
{
# code...
return "Select a file to upload";
}
else
{
$mum_files = count($files['f2']);
for($i=0; $i<$mum_files; $i++)
{
if ( isset($files['f2']['name'][$i]) )
{
$config['file_name'] = time().'-'.$files['f2']['name'][$i];
$this->load->library('upload', $config);
$_FILES['f2']['name']= $files['f2']['name']["$i"];
$_FILES['f2']['type']= $files['f2']['type']["$i"];
$_FILES['f2']['tmp_name']= $files['f2']['tmp_name']["$i"];
$_FILES['f2']['error']= $files['f2']['error']["$i"];
$_FILES['f2']['size']= $files['f2']['size']["$i"];
$filename = rand().'-'.$_FILES['f2']['name'];
if (!empty($this->upload->do_upload('f2')))
{
$dataInfo[] = $this->upload->data();
$all_imgs = '';
if ( count($dataInfo) > 0) {
# code...
foreach ($dataInfo as $info) {
# code...
$all_imgs .= $info['file_name'];
$all_imgs .= ',';
}
}
}
}
}
}
}
else{
$all_imgs = "";
}
}
}
else{
$all_imgs = $this->session->userdata('image');
}
$this->db->insert('table_name', $all_imgs);
The problem I am facing in this code is Think suppose if I am adding 7 images, but it's showing only 5 images in database it's not taking more then five and also I want to know while editing the form if I don't want to change the image then it should remain same image so i have stored the old image in session and checking if it is empty then only it should session variable .
But In my code if I will not upload new one If I keep old image as then it will save blank
To avoid the offset error, inside of for loop you need to check if that array index is set or not:
Here I have a demo code to upload multiple files in CodeIgniter:
views/stack_view.php
<?php if ($this->session->flashdata('status')) { ?>
<h5><?=$this->session->flashdata('status')?>: <?=$this->session->flashdata('message')?></h5>
<?php } ?>
<?=form_open_multipart('stack', array('id' => 'my_id'))?>
<input type="file" name="userfile[]" size="40" multiple/>
<input type="submit" name="submit" value="Upload">
<?=form_close()?>
controllers/Stack.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Stack extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper(array('form', 'url'));
}
public function index()
{
if ($this->input->post('submit')) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$files = $_FILES;
if ($files['userfile']['name'][0] == '' ) {
# code...
$this->session->set_flashdata('status', 'error');
$this->session->set_flashdata('message', "Select a file to upload");
}
else
{
$mum_files = count($files['userfile']);
$dataInfo = array();
for($i=0; $i<$mum_files; $i++)
{
if ( isset($files['userfile']['name'][$i]) ) {
$config['file_name'] = time().'-'.$files['userfile']['name'][$i];
$this->load->library('upload', $config);
$_FILES['userfile']['name']= $files['userfile']['name']["$i"];
$_FILES['userfile']['type']= $files['userfile']['type']["$i"];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name']["$i"];
$_FILES['userfile']['error']= $files['userfile']['error']["$i"];
$_FILES['userfile']['size']= $files['userfile']['size']["$i"];
$filename = rand().'-'.$_FILES['userfile']['name'];
if ( ! $this->upload->do_upload('userfile'))
{
$error_message = $this->upload->display_errors();
$this->session->set_flashdata('status', 'error');
$this->session->set_flashdata('message', "$error_message");
}
else
{
//$data = array('upload_data' => $this->upload->data());
$this->session->set_flashdata('status', 'success');
$this->session->set_flashdata('message', "Files upload is success");
}
$dataInfo[] = $this->upload->data(); //all the info about the uploaded files are stored in this array
}
}
//here you can insert all the info about uploaded file into database using $dataInfo
$all_imgs = '';
if ( count($dataInfo) > 0) {
# code...
foreach ($dataInfo as $info) {
# code...
$all_imgs .= $info['file_name'];
$all_imgs .= ',';
}
}
$insert_data = array(
'your_column_name' => rtrim($all_imgs,",")
);
$this->db->insert('your_table_name', $insert_data);
}
}
$this->load->view('stack_view');
}
}
Try this script and I hope you will get some help from this.
This is working script try to upload it
public function upload()
{
$this->load->library('session');
if ( ! empty($_FILES))
{
$config['upload_path'] = "assets/uploads/";
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = 5120; //limit only 5 Mb
$this->load->library('upload');
$files = $_FILES;;
$number_of_files = count($_FILES['files']['name']);
$errors = 0;
$myname = $this->input->post('ad_title');
for ($i = 0; $i < $number_of_files; $i++)
{
//$randVal = rand(450,4550).time('d-y-m');
$filename = basename($files['files']['name'][$i]);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = md5($filename.''.time('d-y-m')).'.'.$extension;
$_FILES['files']['name'] = $new; //$files['files']['name'][$i];
$_FILES['files']['type'] = $files['files']['type'][$i];
$_FILES['files']['tmp_name'] = $files['files']['tmp_name'][$i];
$_FILES['files']['error'] = $files['files']['error'][$i];
$_FILES['files']['size'] = $files['files']['size'][$i];
$image = array('upload_data' => $this->upload->data());
$image_name = $_FILES['files']['name'];
$ip = $this->input->ip_address();
$this->session->set_userdata("userIP",$ip);
//$this->session->unset_userdata("userIP");
$Dval = array(
"filename" => $image_name,
"ip" => $this->input->ip_address()
);
$this->member_model->tmp_image($Dval);
$this->upload->initialize($config);
if ( $this->upload->do_upload("files"))
{
$errors++;
$data = $this->upload->data();
echo json_encode($data['file_name']);
//code is for thumbnail and watermark on images
//$this->watermark($data['full_path']);
//$myPathfT = $config1['upload_path'] = "./assets/thumbs/".$aDir;
//mkdir($myPathfT);b
$config1 = array();
$config1['image_library'] = 'gd2';
$config1['source_image'] = $data['full_path'];
$config1['new_image'] = 'assets/uploads/thumbs/';
$config1['create_thumb'] = false;
$config1['quality'] = 50;
$config1['height'] = 150;
$config1['width'] = 150;
$this->load->library('image_lib',$config1);
$this->image_lib->initialize($config1);
$this->image_lib->resize();
$this->image_lib->clear();
}
}
if ($errors > 0)
{
//echo "Data Transferred";
}
}
elseif ($this->input->post('file_to_remove'))
{
$aDir = $this->session->userdata('Dir');
$file_to_remove = $this->input->post('file_to_remove');
unlink("./assets/mainFilesData/$aDir/" . $file_to_remove);
$array = $this->session->userdata('photo');
$dataF = array_diff($array, array($file_to_remove));
$this->session->set_userdata('photo',$dataF);
}
else
{
$this->listFiles();
}
}

Photo Upload together with some data won't work. I used batch_insert in my model

This is the View.php file
<input name="u_code[]" required="required" style="margin:0px; ">
<input name="u_name[]" required="required" style="margin:0px; ">
<input name="u_address[]" required="required" style="margin:0px; ">
<input name="photo[]" required="required" style="margin:0px; ">
This is my Controller inserting multiple data but I want to include upload photo.Unfortunately it will not run.
My table has a field for User ID, User Code, Username, User address the lastly the photo of each user.
function user_add()
{
if ($_POST)
{
$u_id =$this->input->post('u_id');
$u_code =$this->input->post('u_code');
$u_name =$this->input->post('u_name');
$u_address = $this->input->post('u_address');
if(!empty($_FILES['photo']['name']))
{
$upload = $this->_do_upload();
$data['photo'] = $upload;
} $data = array();
for ($i = 0; $i < count($this->input->post('u_id')); $i++)
{
$data[$i] = array(
'u_id' => $u_id[$i],
'u_code' => $u_code[$i],
'u_name' => $u_name[$i],
'u_address' => $u_address[$i],
);
}
$insert = $this->user_model->user_add($data);
echo json_encode(array("status" => TRUE));
}
}
This part is the function to upload photo.
public function photo_upload()
{
$config['upload_path'] = 'upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100; //set max size allowed in Kilobyte
$config['max_width'] = 1000; // set max width image allowed
$config['max_height'] = 1000; // set max height allowed
$config['file_name'] = round(microtime(true) * 1000); //just milisecond timestamp fot unique name
$this->load->library('upload', $config);
if(!$this->upload->photo_upload('photo')) //upload and validate
{
$data['inputerror'][] = 'photo';
$data['error_string'][] = 'Upload error: '.$this->upload->display_errors('',''); //show ajax error
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
return $this->upload->data('file_name');
}
**Model:**
public function user_add($data)
{
$this->db->insert_batch($this->table, $data);
return $this->db->insert_id();
}
This is the Actual forms picture:

why image upload through ajax isn't working

I am trying to upload image through ajax so as to see uploaded image in its specific block before save button in clicked. Searching net I found the following code and I tried it. It works fine but when I do upload the image isn't uploaded.
html
<form id="overflow_imgupload" method="post" enctype="multipart/form-data" action="">
<input type="hidden" name="position" value="" class="position"/>
<input type="file" name="imgupload" id="imgupload" value="Upload Image" class="span12"/>
<a id="btn_imgupload" onclick="return ajaxFileUpload();">Upload</a>
<a id="closeimg" >X</a>
</form>
">
function ajaxFileUpload(){
$("#loading")
.ajaxStart(function(){
$(this).show();
})
.ajaxComplete(function(){
$(this).hide();
});
$.ajaxFileUpload({
url:'<?php echo site_url('doajaxfileupload') ?>',
secureuri:false,
fileElementId:'imgupload',
dataType: 'html',
success: function (data, status){
console.log(data);
if(typeof(data.error) != 'undefined'){
if(data.error != ''){
alert(data.error);
}else{
alert(data.msg);
}
}
},
error: function (data, status, e){
alert(e);
}
})
return false;
}
in doajaxfileupload.php
<?php
class Doajaxfileupload extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
//$this->load->library('upload');
}
function index(){
$error = "";
$msg = "";
$fileElementName = 'imgupload';
if(!empty($_FILES[$fileElementName]['error']))
{
switch($_FILES[$fileElementName]['error'])
{
case '1':
$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case '2':
$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case '3':
$error = 'The uploaded file was only partially uploaded';
break;
case '4':
$error = 'No file was uploaded.';
break;
case '6':
$error = 'Missing a temporary folder';
break;
case '7':
$error = 'Failed to write file to disk';
break;
case '8':
$error = 'File upload stopped by extension';
break;
case '999':
default:
$error = 'No error code avaiable';
}
}elseif(empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none')
{
$error = 'No file was uploaded..';
}else
{ //$msg .= $_FILES[$fileElementName]['name'];
$config['allowed_types'] = 'jpg|png|jpeg|bmp|gif';
$config['upload_path'] = './uploaded_files/';
$config['max_width'] = '720';
$config['max_height'] = '240';
$config['min_width'] = '325';
$config['min_height'] = '240';
$this->load->library('upload',$config);
if ($this->upload->do_upload($_FILES[$fileElementName]['name'])) {
$msg .= "Upload success!";
} else {
$msg .= "UPoloadfailes";
}
}
echo "{";
echo "error: '" . $error . "',\n";
echo "msg: '" . $msg . "'\n";
echo "}";
}
}
?>
every time it alerts UPoloadfailes.why??
any help/suggestion is welcome.thanks in advance.
I don't know why but when i use move_uploaded_file it works.
In doajaxfileupload.php else portion
$extension = end(explode('.', $_FILES[$fileElementName]['name']));
$uploaddir = './uploaded_files/temp/';
$file = $uploaddir .'default_'.rand(1,999).'_'.time().'.'.$extension;
if (move_uploaded_file($_FILES[$fileElementName]['tmp_name'], $file)) {
$msg .= $this->input->post('position').','.$file;
} else {
$msg .= "error";
}
Can anyone suggest me why CI upload didn't work and why this PHP move_uploaded_file worked ??

Resources