Magento – Add custom button to upload a file

backendcontrollersupload

I would like to add a custom button in a backend grid page, that let me upload a file in Magento.

So basically it should give me a "file selector" and then file should be processed in a controller.

Can you point out to some tutorial or any Magento default module where I can get an "inspiration" ?

Best Answer

Try this.. In you block-form

$fieldset->addField('file', 'file', array(
            'label'     => Mage::helper('foundation')->__('CSV'),
            'class'     => 'disable',
            'required'  => true,
            'name'      => 'file',
            ));

And in your controller

public function saveAction()
    {
        if ($data = $this->getRequest()->getPost()) {
            if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
                try
                {
                    $path = Mage::getBaseDir().DS.'csv'.DS;  //desitnation directory
                    $fname = $_FILES['file']['name']; //file name
                    $fullname = $path.$fname;
                    $uploader = new Varien_File_Uploader('file'); //load class
                    $uploader->setAllowedExtensions(array('CSV','csv')); //Allowed extension for file
                    $uploader->setAllowCreateFolders(true); //for creating the directory if not exists
                    $uploader->setAllowRenameFiles(false);
                    $uploader->setFilesDispersion(false);
                    $uploader->save($path, $fname); //save the
                }
                catch (Exception $e)
                {
                    $fileType = "Invalid file format";
                }
            }
        }
        if ($fileType == "Invalid file format") {
            Mage::getSingleton('adminhtml/session')->addError(Mage::helper('foundation')->__($fname." Invalid file format"));
            $this->_redirect('*/*/');
            return;
        }

........... I have done my changes as per the my requirement, you can try yours,

Hope this will help you