Uploading an image with Code Igniter? - codeigniter

I'm trying to set a site up so I can upload images using a web form in Code Igniter(CI). I'm not getting any errors but the file is not being saved either. I wanted to know if those that were successful in uploading images could help explain what might be the issue?
View:
<?php
echo form_open_multipart('admin/galleryUpload') . "\n";
echo "<div class='span-8'><span class='text'>Image:</span>" . form_upload('uploadImg') . "</div>";
foreach ($gallery as $picture)
{
$order[] = $picture->order;
}
$order[] = count($order) + 1;
echo "<div class='span-6 last'><span>Image Order #:</span>" . form_dropdown('order', $order) . "</div><div class='span-14'> </div>";
$conf = array('name' => 'alt_text', 'size' => '75');
echo "<div class='span-14 last'><span>Discription:</span>" . form_input($conf) . "<br /></div>";
echo form_hidden('propertyID', "$propertyID");
echo form_submit('upload', 'Upload');
echo form_close();
?>
Controller:
class Admin extends Controller
{
function galleryUpload()
{
if (! $this->session->userdata('is_admin'))
{
redirect('admin/index');
}
else
{
$this->load->model('admin_model');
$this->admin_model->imgUpload();
}
}
}
Model:
class Admin_model extends Model
{
function imgUpload()
{
$id = $this->input->post('propertyID');
$order = $this->input->post('order');
$alt_text = $this->input->post('alt_text');
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
//'upload_path' => '../' . $this->imgPath($id),
'upload_path' => '../img/galleries/temp/',
'max_size' => '5000', // 5MB files max
);
$this->load->library('upload', $config);
$this->upload->do_upload();
$image_data = $this->upload->data();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->imgPath($id) . '/thumbs',
'maintain_ratio' => TRUE,
'width' => '60'
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
}

From the user guide:
By default the upload routine expects the file to come from a form
field called userfile, and the form must be a multipart type
So you either have to change the name of the form field to userfile:
form_upload('userfile')
or pass the name of your form field to do_upload:
$this->upload->do_upload('uploadImg');

Related

Codeigniter Single Image into Multiple Resize ie 350*250, 50*50 and original size

I am new to CodeIgniter. This is what I want to do:
Resize the product image into 350*250, 50*50 and origional image while uploading the image in add product from admin.
All these three images in the three different folders.
Here is my code-
public function products()
{
$config=array();
$config['upload_path']="./uploads/";
$config['allowed_types']="jpg|jpeg|gif|png";
$this->load->library('upload',$config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$file_data = $this->upload->data();
$data1['img']=base_url().'images/'.$file_data['file_name'];
$data_image = array(
'agenda_id' => $this->input->post('agenda_id'),
'file' => $file_data['file_name']
);
$config['image_library']='gd2';
$config['source_image']='./uploads/'.$file_data["file_name"];
$config['create_thumb']=FALSE;
$config['maintain_ratio']=FALSE;
$config['quality']='60%';
$config['width']=350;
$config['height']=250;
$config['new_image']='./uploads350/'.$file_data["file_name"];
$this->upload->initialize($config);
$this->load->library('image_lib',$config);
$this->image_lib->resize();
}
$this->load->model("Admin_model");
$data= array(
"Type" =>$this->input->post("Type"),
"Brand" =>$this->input->post("Brand"),
"Product_Name" =>$this->input->post("Product_Name"),
"Price" =>$this->input->post("Price"),
"Image"=>$data_image['file']
);
$this->Admin_model->admin($data);
$this->session->set_flashdata('message', 'Product added successfully');
redirect('Admin/product_list');
}
This should work fine (haven't tested). Just make sure the folders exist. Also, if I were you I'd probably keep everything in the same folder and just prepend the size afterwords like some_image_50.jpg:
public function products() {
$config = array();
$config['upload_path'] = "./uploads/";
$config['allowed_types'] = "jpg|jpeg|gif|png";
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors()); // do something with this...
// e.g. show_error($this->upload->display_errors());
} else {
$file_data = $this->upload->data();
$data1['img'] = base_url() . 'images/' . $file_data['file_name'];
$data_image = array(
'agenda_id' => $this->input->post('agenda_id'),
'file' => $file_data['file_name']
);
//$config['image_library'] = 'gd2'; (default; not needed)
$this->load->library('image_lib');
$cfg['source_image'] = './uploads/' . $file_data["file_name"];
$cfg['create_thumb'] = FALSE;
$cfg['maintain_ratio'] = FALSE;
$cfg['quality'] = '60%';
$cfg['width'] = 350;
$cfg['height'] = 250;
$cfg['new_image'] = './uploads350/' . $file_data["file_name"];
//$this->upload->initialize($config); why??
$this->image_lib->initialize($cfg);
$this->image_lib->resize();
// the following vars will override certain vars above and keep the ones we haven't overridden
$cfg['width'] = 50;
$cfg['height'] = 50;
$cfg['new_image'] = './uploads50/' . $file_data["file_name"]; // make sure folder exists
$this->image_lib->initialize($cfg);
$this->image_lib->resize();
}
$this->load->model("Admin_model");
$data = array(
"Type" => $this->input->post("Type"),
"Brand" => $this->input->post("Brand"),
"Product_Name" => $this->input->post("Product_Name"),
"Price" => $this->input->post("Price"),
"Image" => $data_image['file']
);
$this->Admin_model->admin($data);
$this->session->set_flashdata('message', 'Product added successfully');
redirect('Admin/product_list');
}

getting an error Undefined property: stdClass::$id

I've issue with my CMS whenever I tried to Add new page with the following line of code
<?php echo form_open_multipart('admin/page/edit/'. $page->id); ?>
it gives me error
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$id
Filename: page/edit.php
Line Number: 5
my edit function is this which perform add & update functionality
public function edit($id = NULL) {
//Fetch a page or set new one
if ($id) {
$this->data['page'] = $this->page_m->get($id);
count($this->data['page']) || $this->data['errors'][] = 'Page Could not be found';
} else {
$this->data['page'] = $this->page_m->get_new();
}
$id == NULL || $this->data['page'] = $this->page_m->get($id);
//Pages for dropdown
$this->data['pages_no_parents'] = $this->page_m->get_no_parents();
//dump($this->data['pages_no_parents']);
//Setup form
$rules = $this->page_m->rules;
$this->form_validation->set_rules($rules);
//Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->page_m->array_from_post(array(
'title',
'slug',
'order',
'body',
'template',
'parent_id',
'filename'
));
/* * ***********WORKING FOR IMAGE UPLOAD AND SAVE PATH TO DATABASE*************** */
if (!empty($_FILES['filename'])) {
$fdata = $this->do_upload('filename'); /// you are passing the parameter here
$data['filename'] = base_url() . 'uploads/' . $fdata;
}
$this->page_m->save($data, $id);
// echo '<pre>' . $this->db->last_query() . '</pre>';
redirect('admin/page');
}
//Load the view
$this->data['subview'] = 'admin/page/edit';
$this->load->view('admin/_layout_main', $this->data);
}
public function do_upload($field_name) { // but not retriveing here do this
$field_name = 'filename';
$config = array(
'allowed_types' => '*',
'max_size' => '1024',
'max_width' => '1024',
'max_height' => '768',
'upload_path' => './uploads/'
);
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload($field_name)) {
echo $this->upload->display_errors();
die();
$this->data['error'] = array('error' => $this->upload->display_errors());
//$this->data['subview'] = 'admin/page/edit';
//$this->load->view('admin/_layout_main', $this->data);
} else {
$fInfo = $this->upload->data();
//return $fInfo['file_path'].$fInfo['file_name'];
// $this->filename = $fInfo;
return $fInfo['file_name'];
}
}
<?php echo form_open_multipart('admin/page/edit/'. ((isset($page->id)) ? $page->id : '')); ?>
As I mentioned in my comment, if you are creating a new record (I assume:) your page object will not have an id yet, so you just have to do a quick check to make sure it exists and if not output an empty string.

Varien_File_Uploader is not uploading files in custom module in magento

I am trying to save the images in my module but the images are not saving from the form.
$uploader = new Varien_File_Uploader('image'); this code is not working I dont know why. The loop breaks on this line and the control get out of the loop from here. How can I save the images.
Here is my save function in the controller
public function saveAction()
{
if ($this->getRequest()->getPost())
{
try
{
$postData = $this->getRequest()->getPost();
//echo "<pre>";print_r($postData); exit;
$articleModel = Mage::getModel('blog/article');
$imgFilename = NULL;
if($_FILES['image']['name'] != '')
{//echo "<pre>"; echo count($_FILES['image']['name']);
foreach($_FILES['image']['name'] as $_FILES['image']['name'])
{
//print_r($_FILES['image']['name']);
try
{ echo "1";
$uploader = new Varien_File_Uploader('image'); echo "hi";
//print_r($uploader);exit;
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png','flv'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$uploader->setAllowCreateFolders(true);
// Set media as the upload dir
$media_path = Mage::getBaseDir('media') . DS . 'blog' . DS;
$imgFilename = time() . $postData['image'];
// Upload the image
//$uploader->save($media_path, $_FILES['image']['name']);echo "4";
$uploader->save($media_path, $imgFilename);
}
catch (Exception $e)
{
Mage::log($e);
$this->_redirectError(502);
}
$data['image'] = $imgFilename;
}
}
else
{
if(isset($data['image']['delete']) && $data['image']['delete'] == 1)
$data['image'] = '';
else
unset($data['image']);
}
//echo "out"; exit;
if( $this->getRequest()->getParam('id') <= 0 )
$articleModel->setCreatedTime(
Mage::getSingleton('core/date')
->gmtDate());
$articleModel
->addData($postData)
->setUpdatedTime(
Mage::getSingleton('core/date')
->gmtDate())
->setId($this->getRequest()->getParam('id'))
->save();
$lastid = $articleModel->getId();
if($data['image'] != '')
{
foreach($data['image'] as $img)
{
$imageModel=Mage::getModel('blog/image');
$imageModel->setArticleId($lastid)->setImage($data['image'])->save();
}
}
Mage::getSingleton('adminhtml/session')
->addSuccess('successfully saved');
Mage::getSingleton('adminhtml/session')
->setarticleData(false);
$this->_redirect('*/*/');
//return;
if ($this->getRequest()->getParam('back'))
{
$this->_redirect('*/*/edit',array('id' => $articleModel->getId()));
return;
}
}
catch (Exception $e)
{
Mage::getSingleton('adminhtml/session')
->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')
->setarticleData($this->getRequest()
->getPost());
$this->_redirect('*/*/edit',
array('id' => $this->getRequest()
->getParam('id')));
return;
}
}
$this->_redirect('*/*/');
}
and here is my form for the image
<?php
class Vertax_Blog_Block_Adminhtml_Article_Edit_Tab_Image extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('image_form',
array('legend'=>'image'));
//$fieldset->addType('image', Mage::getConfig()->getBlockClassName('blog/adminhtml_article_helper_image'));
$fieldset->addType('image', 'Vertax_Blog_Block_Adminhtml_Article_Helper_Image');
$fieldset->addField('image', 'image', array(
'label' => 'Image',
'required' => false,
'name' => 'image[]',
'multiple' => 'multiple',
'mulitple' => true,
));
if (Mage::getSingleton('adminhtml/session')->getBlogPostData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getBlogPostData());
Mage::getSingleton('adminhtml/session')->setBlogPostData(null);
} elseif (Mage::registry('article_data')) {
$form->setValues(Mage::registry('article_data')->getData());
}
return parent::_prepareForm();
}
}
?>
$uploader = new Mage_Core_Model_File_Uploader(
array(
'name' => $_FILES['galleryImage']['name'][$i],
'type' => $_FILES['galleryImage']['type'][$i],
'tmp_name' => $_FILES['galleryImage']['tmp_name'][$i],
'error' => $_FILES['galleryImage']['error'][$i],
'size' => $_FILES['galleryImage']['size'][$i]
));
Waseem,please try code for upload image..
$uploader = new Mage_Core_Model_File_Uploader('image');
$uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
$uploader->setFilesDispersion(true);
$media_path = Mage::getBaseDir('media') . DS . 'blog' . DS;
$imgFilename = time() . $postData['image'];
// Upload the image
//$uploader->save($media_path, $_FILES['image']['name']);echo "4";
$uploader->save($media_path, $imgFilename);
there was a problem in your code while adding fieldset
$fieldset->addField('image', 'image', array(
'label' => 'Image',
'required' => false,
'name' => 'image[]',
'multiple' => 'multiple',
'mulitple' => true,
));
here you had set the name to image[] which in turn will return the array as $_FILES['image][name][], $_FILES['image][tmp_name][].
If you want to upload single file then set 'name' = 'image' or see this question
Try to use
$uploader = new Varien_File_Uploader($_FILES['image']);
instead of what you use currently.

Drupal Ajax Form Ajax Form to pull two different views

I have two different views that need to be toggled on a node page. I cannot put these two views together so I have created a form that will basically take the values of the form that I create, and send them as arguments to the view and display the view. I am attempting to do with this ajax. It works fine but the problem is the second time I run the form it does not refresh or update that view.
function photoflight_albums() {
photoflight_gallery_themes();
$output = render(drupal_get_form('photoflight_gallery_form'));
$output .= "<div id='gallery-ajax-wrapper'>";
$output .= views_embed_view('gallery', 'default');
$output .= "</div>";
return $output;
}
//Grabs the node titles
function photoflight_gallery_themes(){
$type = "photo_theme";
$theme_list = array();
$nodes = node_load_multiple(array(), array('type' => $type));
foreach($nodes as $themes){
$theme_list[$themes->title] = $themes->title;
}
return $theme_list;
}
//Form calls back to the function above to the gallery-ajax-wrapper div output above
function photoflight_gallery_form($form, &$form_state){
$form = array();
$form['themes'] = array(
'#type' => 'select',
'#options' => array(photoflight_gallery_themes()),
'#ajax' => array(
'callback' => 'photoflight_simplest_callback',
'wrapper' => 'gallery-ajax-wrapper',
),
);
//debug($form);
return $form;
}
//Ajax callback
function photoflight_simplest_callback($form, $form_state) {
$view = views_get_view('gallery');
$args = array( 'title' => $form_state['values']['themes']);
$view->set_exposed_input($args);
$output = $view->preview('default', $args);
return array("#markup" => $output);
}
The issue was that it was removing the HTML element so the second call had no HTML to replace. Changed to either use ajax update or on the call back wrap the return in the div again
function photoflight_simplest_callback($form, $form_state) {
$view = views_get_view('gallery');
$args = array( 'title' => $form_state['values']['themes']);
$view->set_exposed_input($args);
$output = '<div id="gallery-ajax-wrapper">';
$output .= $view->preview('default', $args);
$output .= '</div>';
return array("#markup" => $output);
}

error resizeing images in a loop in codeigniter

i have a problem while uploading and resizing images in a loop.
can anyone please provide me the working sample of code of codeigniter for uploading and resizing at the same time in a loop.
I want to upload and resize images uploaded from the form. There will be more than 1 images so i have to upload them in loop.
My code first uploads the image then resizes it. 1ts images is uploaded and resized correctly but during 2nd loop the image is uploaded but not resized. It throws this error:
Your server does not support the GD
function required to process this type
of image.
I have tried the clear function too
$this->image_lib->clear();
can anyone please help
Dont load image_lib multiple times. Add image_lib in autoload libs and change
$this->load->library('image_lib', $config);
to
$this->image_lib->initialize($config);
I had the same problem but this seemed to work:
// Do upload
if (! $this->upload->do_upload($image_name)) {
// return errors
return array('errors' => $this->upload->display_errors());
}
$data = $this->upload->data();
$config_manip = array(
'image_library' => 'gd2',
'source_image' => "./assets/uploads/{$data['file_name']}",
'new_image' => "./assets/uploads/thumbs/{$data['file_name']}",
'create_thumb' => true,
'thumb_marker' => '',
'maintain_ratio' => true,
'width' => 140,
'height' => 140
);
// Create thumbnail
$this->load->library('image_lib');
$this->image_lib->resize();
$this->image_lib->clear();
$this->image_lib->initialize($config_manip);
if ( ! $this->image_lib->resize()){
return array('errors' => $this->image_lib->display_errors());
}
Notice the Create Thumbnail goes:
Load Library,
Resize Image,
CLEAR,
Initialize Config
I was putting the clear after the initialize which was causing the same error you're getting.
Here is a working code from my image gallery controller. This function uploads a batch of images, resizes them and saves them to database.
public function create_photo_batch() {
$this->load->library('image_lib');
$this->load->library('upload');
// Get albums list for dropdown
$this->data['albums'] = $this->gallery_m->get_albums_list();
if(isset($_FILES['images']) && $_FILES['images']['size'] > 0) {
$album_id = $this->input->post('albumid');
$images = array();
$ret = array();
// Upload
$files = $_FILES['images'];
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$upload_config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => realpath(APPPATH . "../uploads/gallery"),
'max_size' => 5000,
'remove_spaces' => TRUE,
'file_name' => md5(time())
);
$this->upload->initialize($upload_config);
if ($this->upload->do_upload('images[]')) {
$image_data = $this->upload->data();
$images[] = $image_data['file_name'];
} else {
$this->session->set_flashdata('error', $this->upload->display_errors() );
redirect('admin/gallery/create_photo_batch');
}
}
// Resize
foreach ($images as $image) {
$resize_config = array(
'source_image' => realpath(APPPATH . '../uploads/gallery') .'/'. $image,
'new_image' => realpath(APPPATH . '../uploads/gallery/thumbs'),
'maintain_ratio' => TRUE,
'width' => 500,
'height' => 500
);
$this->image_lib->initialize($resize_config);
if ( ! $this->image_lib->resize() ) {
echo $this->image_lib->display_errors();
die;
}
$this->image_lib->clear();
}
// Save to db
foreach ($images as $image) {
$ret[] = array(
'AlbumID' => (int) $album_id,
'Url' => $image,
'IsActive' => 1
);
}
$this->gallery_m->save_images($ret);
redirect('admin/gallery/album/'.$album_id);
}
//Load view
$this->data['subview'] = 'admin/gallery/photo_upload_batch_view';
$this->load->view('admin/_layout_main', $this->data);
}
Your error message suggest that it's not the loop that is the problem, but rather that the 2nd file is of a different filetype than the 1st. And that the underlying server don't have the needed libraries (http://www.libgd.org/Main_Page) installed to handle that file type.
$config['image_library'] = 'gd2';
$config['source_image'] = './assets/upload_images/A.jpg';
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 1600;
$config['height'] = 900;
$config['new_image'] = './assets/upload_images/'.$randy;
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
I had same problem but solved these by this code.

Resources