Zend Framework: Upload file by using Zend Form Element

♀尐吖头ヾ 提交于 2019-12-02 09:53:20

First of all, rather than extending Zend_Validate_Abstract, you should be extending Zend_Form with an init() method where you can create your form elements:

<?php

class Application_Form_ContactMethodSelected extends Zend_Form
{
    public function init()
    {
    }
}

Now that you have an actual form to work with, you can add things like your File upload element:

<?php

class Application_Form_ContactMethodSelected extends Zend_Form
{
    public function init()
    {
        $this->setAttrib('enctype', 'multipart/form-data');

        $file = new Zend_Form_Element_File('file');
        $file->setLabel('File')
            ->setDestination(APPLICATION_PATH . '/tmp')
            ->setRequired(true);

        $submit = new Zend_Form_Element_Submit('submit');
        $submit->setLabel('Upload');

        $this->addElements(array($file, $submit));
    }
}

Now that you have a form with some elements, you can use it in your controller:

<?php

class IndexController extends Zend_Controller_Action 
{
    public function indexAction() 
    {
        $form = new Application_Form_ContactMethodSelected();

        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if ($form->isValid($formData)) {

                // success - do something with the uploaded file
                $uploadedData = $form->getValues();
                $fullFilePath = $form->file->getFileName();

                Zend_Debug::dump($uploadedData, '$uploadedData');
                Zend_Debug::dump($fullFilePath, '$fullFilePath');

                echo "done";
                exit;

            } else {
                $form->populate($formData);
            }
        }

        $this->view->form = $form;
    }
}

And in your view script, you can display your form:

<h1>My upload form</h1>
<?php echo $this->form; ?>

try this:

//Element Attachment
$this->addElement('file', 'attachment', array('label' => 'Attachment'));
$this->attachment->setDestination(APPLICATION_PATH . "/tmp/");
$this->attachment->addValidator('NotExists', false);

or

$attachment = $this->createElement('file', 'attachment', array('label' => 'Attachment'))
->attachment->setDestination(APPLICATION_PATH . "/tmp/")
->addValidator('NotExists', false);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!