简体   繁体   中英

How to update uploaded file in magento

This is the final challenge for me in completing my study about magento grid.

I have a file upload were I am able to upload and delete PDF file, both the path from DB and the file in the directory. I also successfully override the Varien_Data_Form_Element_File to put image before the upload file button. I have posted a lot of questions about this and I am now on the way of completing it.

The only thorn that I am facing right now is the update of the file. I am able to update the path on the database and upload the updated file on the directory. However, the old file is not deleted. And if the new and old file has the same file name, the new file will be automatically renamed by the server by putting an underscore and one (_1) at the end of the file name.

QUESTION:

How do I delete the old uploaded file on the server during update?

Below is my controller.

public function saveAction() {
    $post_data=$this->getRequest()->getPost();

    if ($post_data) {
        try {

     //save file to the destination folder   
            if (isset($_FILES)){

                if ($_FILES['file_path']['name']) {

                    $path = Mage::getBaseDir('media') . DS . 'rts' . DS .'pmadmin'.DS;
                    $uploader = new Varien_File_Uploader('file_path');
                    $uploader->setAllowedExtensions(array('PDF','pdf'));
                    $uploader->setAllowRenameFiles(false);
                    $uploader->setFilesDispersion(false);

                    $date = date("m-d-y");
                    $file_name = $_FILES['file_path']['name'];
                    $str_lc = strtolower($file_name);
                    $get_ext = pathinfo($str_lc, PATHINFO_EXTENSION);
                    $basename = basename($str_lc, '.pdf');
                    $str_rep = preg_replace('/[^a-zA-Z0-9:]/', '_', $basename);
                    $full_name = $str_rep.'_'.$date.'.'.$get_ext;

                    /** 
                    *-------------------------------------------
                    * This line of code is intended to delete the old uploaded file 
                    *-------------------------------------------
                    **/
                        if( $this->getRequest()->getParam('id') > 0 ) {

                            //Specify which model to call
                            $pmadminModel = Mage::getModel('pmadmin/pmadmin');

                            //Retrieve current ID of the file
                            $file_id = $this->getRequest()->getParam('id');

                            //Retrieve speicific file_path from the databse
                            $file_collection = $pmadminModel->getCollection()
                                                            ->addFieldToSelect('file_path')
                                                            ->addFieldToFilter('pmadmin_id', $file_id);

                            foreach ($file_collection as $key) {
                                $key;
                            }
                            $file_name_db = $key->getData('file_path');
                            $file_name_form = $_FILES['file_path']['name'];

                            if ($file_name_db != $file_name_form) {
                                if (file_exists($file_name_db)) {
                                    unlink($file_name_form);
                                }
                            }
                        }
                    /**
                    *-------------------------------------end
                    **/

                    $destFile = $path.$full_name;
                    $filename = $uploader->getNewFileName($destFile);
                    $uploader->save($path, $filename);

                    $post_data['file_path']=$filename;
                }
            }
    //save file path to the database
            $model = Mage::getModel("pmadmin/pmadmin")
            ->addData($post_data)
            ->setId($this->getRequest()->getParam("id"))
            ->save();

            Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("File was successfully saved"));
            Mage::getSingleton("adminhtml/session")->setPmadminData(false);

            if ($this->getRequest()->getParam("back")) {
                $this->_redirect("*/*/edit", array("id" => $model->getId()));
                return;
            }
            $this->_redirect("*/*/");
            return;
        } 
        catch (Exception $e) {
            Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
            Mage::getSingleton("adminhtml/session")->setPmadminData($this->getRequest()->getPost());
            $this->_redirect("*/*/edit", array("id" => $this->getRequest()->getParam("id")));
        return;
        }

    }
    $this->_redirect("*/*/");
}

use this code

 if( $this->getRequest()->getParam('id') > 0  and $_FILES['file_path']['name']) {
                        $filepath = Mage::getBaseDir('media') . DS . 'rts' . DS .'pmadmin'.DS;
                                //Specify which model to call
                                $pmadminModel = Mage::getModel('pmadmin/pmadmin');

                                //Retrieve current ID of the file
                                $file_id = $this->getRequest()->getParam('id');

                                //Retrieve speicific file_path from the databse
                                $file_collection = $pmadminModel->getCollection()
                                                                ->addFieldToSelect('file_path')
                                                                ->addFieldToFilter('pmadmin_id', $file_id);

                                foreach ($file_collection as $key) {
                                    $key;
                                }
                                $file_name_db = $key->getData('file_path');
                                $file_name_form = $_FILES['file_path']['name'];

                                if ($file_name_db != '') {

                                        unlink($filepath.$file_name_form);

                                }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM