How to upload images in custom module like in add product in admin of magento?

4.9k views Asked by At

I am working on magento 1.7 version. I have a custom extension.In this I need to add option to upload multiple images similar to default product extension of magento.

How can I achieve this?

1

There are 1 answers

1
Rajeev K Tomy On

Since you are using a file uploads, you need to add enctype="multipart/form-data" in your edit.php file.(very important)

Now in order to upload an image, your form file should look like this

<?php
class Example_Imageuploader_Block_Adminhtml_Imageuploader_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{  
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form();
        $this->setForm($form);
        $fieldset = $form->addFieldset('Images', array('legend'=>Mage::helper('banner')->__('Example Image')));
        $fieldset->addField('image_1', 'file', array(
            'label'     => Mage::helper('imageuploader')->__('Upload'),
            'value'  => 'image_1',
            'disabled' => false,
            'readonly' => true,                
        )); 
        /*
            repeat this file field instant according to your need
        */                       
    return parent::_prepareForm();                                                    
    }  

}

Now in your controller -> saveAction() add these codes

<?php
    public function saveAction()
    {
        if(isset($_FILES['image_1']['name']) and (file_exists($_FILES['image_1']['tmp_name']))) 
        {                             
            try 
            {
                $path = Mage::getBaseDir('media') . DS . 'banner' . DS;
                $uploader = new Varien_File_Uploader('image_1');

                $uploader
           ->setAllowedExtensions(array('jpg','png','gif','jpeg'));
                $uploader->setAllowRenameFiles(false);
                $uploader->setFilesDispersion(false);
                $destFile = $path.$_FILES[$image]['name'];
                $filename = $uploader->getNewFileName($destFile);
                            $uploader->save($path, $filename);

                $data['img'] = $_FILES['image_1']['name'];
            }
            catch(Exception $e) 
            {

            }
        }
        else 
        {                                                     
            if(isset($data['image_1']['delete']) && $postData['image_1']['delete'] == 1)
                 $data['image_1'] = '';
            else
                 unset($data['image_1']);
        }
    }

You are done !! I think this will give basic idea of uploading an image. Using this make your own custom module. Good luck