如何在自定义模块中上传图像,如在magento的admin中添加产品?

时间:2013-12-21 18:18:55

标签: magento magento-1.7 magento-1.4 adminhtml

我正在研究magento 1.7版本。我有一个自定义扩展。在这里我需要添加选项来上传多个图像,类似于magento的默认产品扩展。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

由于您使用的是文件上传,因此需要在edit.php文件中添加 enctype =“multipart / form-data”。(非常重要)< / p>

现在,为了上传图片,您的表单文件应如下所示

<?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();                                                    
    }  

}

现在在您的控制器中 - &gt; saveAction()添加这些代码

<?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']);
        }
    }

你完成了!!我认为这将提供上传图像的基本思路。使用它可以创建自己的自定义模块。祝你好运