Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [PHP]Zend Framework Zend_Form dodawanie plików.
Forum PHP.pl > Forum > Przedszkole
cykcykacz
Witam, chcę stworzyć formularz z dodawaniem graficznych plików:
1. Liczba plików max 8;
2.zmiana nazwy pliku;
3.zapis nazwy pliku do bazy;
Taki mam formularz:
Kod form:
CODE

public function __construct($options = null)
{
parent::__construct($options);
$this->setName('Sala');

$plik = new Zend_Form_Element_File('foo');
$plik->setLabel('Upload an image:')
->setDestination('c:\xampp\htdocs\asd');
$plik->addValidator('Count', false, array('min' => 1, 'max' => 8));
$plik->addValidator('Size', false, 102400);
$plik->addValidator('Extension', false, 'jpg,png,gif');


$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Wyślij');

$this->addElements(array( $plik, $submit ));
$this->setMethod('post');
$this->setAction(Zend_Controller_Front::getInstance()->getBaseUrl().'/addsala/index');

}

kontroler:
Kod
    public function indexAction()
    {
        $request = $this->getRequest();
        $form = new Form_Addsala();
            if($request->isPost()) {
            if($form->isValid($this->_request->getPost())) {                
                           }
            }
        $this->view->form = $form;
    }

widok:
Kod
<?php echo $this->form;
      echo $this->errorMessage;
?>


W obecnej chwili nie upload-uje mi pliku do podanej ścieżki proszę o pomoc.
darko
To:
->setDestination('c:\xampp\htdocs\asd');
zmień na ścieżkę względną do folderu z odpowiednimi uprawnieniami do zapisu na serwerze (pamiętaj, że pliki będą uploadowane na serwer, a nie na Twój dysk)
cykcykacz
Kod
->setDestination('\testy');

dostaje błąd, chyba nie wiem co to ścieżka względna

Kod
Exception information:
Message: The given destination is no directory or does not exist


Korzystam z xampp
darko
jeśli ma być folder testy, to bardziej: ->setDestination('testy/'); albo w ogóle to wywal z formularza i ustaw w skrypcie obsługującym upload
cykcykacz
Wiem że to jest banalne ale jestem już zmęczony:
adres http://localhost/testy/public/addsala/index

Kod
->setDestination('../../testy/');

Nie pokazuje żadnego błędu ale plik nie zostaje przesłany do celu:).
darko
Czy addsala jest modułem questionmark.gif Jeśli jest, to: ->setDestination('../testy/');
// edit
ale lepiej to setDestination - jak wcześniej wspomniałem - realizować w innej postaci przy uploadzie i kopiowaniu plików
cykcykacz
No ok.. podarowałem sobie:
->setDestination();

Czyli funkcję która ładuje pliki na dysk piszę w kontrolerze tak?
Mam o tym poczytać Zend_File =-> http://framework.zend.com/manual/en/zend.file.html questionmark.gif
darko
Zend_File_Transfer_Adapter_Http
cykcykacz
Witam nadal nie potrafię wgrać pliku korzystam z tego sposobu: http://ahsangill.wordpress.com/2009/02/17/...m_element_file/

Tak wygląda mój formularz:
CODE

<?php
class Form_Addsala extends Zend_Form
{
public function __construct($options = null)
{
parent::__construct($options);
// setting Form name, Form action and Form Ecryption type
$this->setName('document');
$this->setAction("");
$this->setAttrib('enctype', 'multipart/form-data');

// creating object for Zend_Form_Element_File
$doc_file = new Zend_Form_Element_File('doc_path');
$doc_file->setLabel('Document File Path')
->setRequired(true);

// creating object for submit button
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Upload File')
->setAttrib('id', 'submitbutton');

// adding elements to form Object
$this->addElements(array($doc_file, $submit));
}

}


Tak kontroler:
CODE

public function indexAction()
{
$form = new Form_Addsala();
$this->view->form = $form;

if ($this->_request->isPost()) {

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

/* Uploading Document File on Server */
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->setDestination("/uploads/files/");
try {
// upload received file(s)
$upload->receive();
} catch (Zend_File_Transfer_Exception $e) {
$e->getMessage();
}

// so, Finally lets See the Data that we received on Form Submit
$uploadedData = $form->getValues();
Zend_Debug::dump($uploadedData, 'Form Data:');

// you MUST use following functions for knowing about uploaded file
# Returns the file name for 'doc_path' named file element
$name = $upload->getFileName('doc_path');

# Returns the size for 'doc_path' named file element
# Switches of the SI notation to return plain numbers
$upload->setOption(array('useByteString' => false));
$size = $upload->getFileSize('doc_path');

# Returns the mimetype for the 'doc_path' form element
$mimeType = $upload->getMimeType('doc_path');

// following lines are just for being sure that we got data
print "Name of uploaded file: $name
";
print "File Size: $size
";
print "File's Mime Type: $mimeType";

// New Code For Zend Framework :: Rename Uploaded File
$renameFile = 'newName.jpg';

$fullFilePath = '/images/'.$renameFile;

// Rename uploaded file using Zend Framework
$filterFileRename = new Zend_Filter_File_Rename(array('target' => $fullFilePath, 'overwrite' => true));

$filterFileRename -> filter($name);

exit;
}

} else {

// this line will be called if data was not submited
$form->populate($formData);
}
}

Dostaje taki komunikat o błędzie:
Kod
Catchable fatal error: Argument 1 passed to Zend_Form::populate() must be an array, null given, called in C:\xampp\htdocs\testy\application\controllers\AddsalaController.php on line 70 and defined in C:\xampp\htdocs\ZendFramework\library\Zend\Form.php on line 1893
melkorm
Jeżeli nie rozumiesz treści tego błędu to naprawdę nie radzę się brać za Zend'a ... .

Co do tematu $formData musi być tablicą, najwidoczniej nigdzie jej nie deklarujesz.
cykcykacz
Tak masz rację nie potrzebnie wybrałem Framework Zend mam jeszcze za mało wiedzy dotyczącej korzystania z PHP obiektowego itd. W tej chwili wykonuje projekt na zlecenie mam już ok. 70% więc chyba już nie ma sensu się wycofać.
Jeżeli wiesz jak pobrać pliki na dysk albo znasz jakiś tutoriale lub inne rozwiązanie mojego problemu będę wdzięczny.
Pozdrawiam.
melkorm
Wklej strukturę katalogów, wrócę z uczelni to zobaczę co da się zrobić.
cykcykacz
OK już podaje korzystam z xampp C:\xampp\htdocs(jeżeli miało by to w czymś pomóc) teraz struktura katalogów projektu:
-----------
testy
-application
--configs
--controllers
---kontrolery.php
--forms
---formularze.php
--layouts
---layout.phtml
--models
---modele.php
--plugins
---pluginy.php
--views
---helpers
---scripts
----index
-----index.phtml

Bootstrap.php

-library
-public
--------------
Jeżeli mało czytelnie mogę poprawić(chyba znasz tą strukturę).
[EDIT]
Ok coś ruszyłem ale jeszcze nie jest to o co mi chodzi plik się przesłał do podanej lokalizacji ale nie zmienił nazwy
Kod formularza:
CODE

<?php
class Form_Addsala extends Zend_Form
{
public function __construct($options = null)
{
parent::__construct($options);
$this->setName('Sala');
$this->setAttrib('enctype', 'multipart/form-data');

$plik = new Zend_Form_Element_File('foo');
$plik->setLabel('Upload an image:')
->setDestination('../../testy/');
$plik->addValidator('Count', false, array('min' => 1, 'max' => 6));
$plik->addValidator('Size', false, 102400);
$plik->addValidator('Extension', false, 'jpg,png,gif');


$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Wyślij');

$this->addElements(array( $plik, $submit ));
$this->setMethod('post');
$this->setAction(Zend_Controller_Front::getInstance()->getBaseUrl().'/addsala/index');

}
}

Kod kontrolera:
CODE

<?php

class AddsalaController extends Zend_Controller_Action
{

public function init()
{
/* Initialize action controller here */
}

public function indexAction()
{
$request = $this->getRequest();
$form = new Form_Addsala();
if ($this->_request->isPost()) {

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

/* Uploading Document File on Server */
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->setDestination("../../testy/");
try {
// upload received file(s)
$upload->receive();
} catch (Zend_File_Transfer_Exception $e) {
$e->getMessage();
}

// so, Finally lets See the Data that we received on Form Submit
$uploadedData = $form->getValues();
Zend_Debug::dump($uploadedData, 'Form Data:');

// you MUST use following functions for knowing about uploaded file
# Returns the file name for 'doc_path' named file element
$name = $upload->getFileName('doc_path');

# Returns the size for 'doc_path' named file element
# Switches of the SI notation to return plain numbers
$upload->setOption(array('useByteString' => false));
$size = $upload->getFileSize('doc_path');

# Returns the mimetype for the 'doc_path' form element
$mimeType = $upload->getMimeType('doc_path');

// following lines are just for being sure that we got data
print "Name of uploaded file: $name
";
print "File Size: $size
";
print "File's Mime Type: $mimeType";

// New Code For Zend Framework :: Rename Uploaded File
$renameFile = 'newName.jpg';

$fullFilePath = '/images/'.$renameFile;

// Rename uploaded file using Zend Framework
$filterFileRename = new Zend_Filter_File_Rename(array('target' => $fullFilePath, 'overwrite' => true));

$filterFileRename -> filter($name);

exit;
}

} else {

// this line will be called if data was not submited
$form->populate($formData);
}
}
}

Na stronie wyświetla informacje:
Kod
Form Data: array(2) {
  ["foo"] => string(11) "dj-logo.gif"
  ["submit"] => string(7) "Wyślij"
}

Fatal error: Call to undefined method Zend_File_Transfer_Adapter_Http::setOption() in C:\xampp\htdocs\testy\application\controllers\AddsalaController.php on line 40

Chyba chodzi o to że nie może zidentyfikować metody Zend_File_Transfer_Adapter_Http.
melkorm
Zaquotuj tą linijkę (40)
  1. $upload->setOption(array('useByteString' => false));


I zobacz czy wtedy będzie działać, bo ogólnie bez tego powinno śmignąć, dziwny ogólnie ten skrypt - niby gotowiec a tyle błędów winksmiley.jpg
zend
Pomijając kwestię ścieżek (ustaw tą co nie było błędów), w pierwszym poście zabrakło Ci $form -> getValues(); w tej metodzie następuje upload plików
CzarnyGsm
Tutaj ewidentny błąd miałeś po stronie ścieżki pliku tj. setDestination. Niżej zamieszczam moje rozwiązanie (dla potomnych). Kod sprawdzony i działa na najnowszej wersji Zend.
Kod
//File application/form/UploadImage.php
class Application_Form_UploadImage extends Zend_Form
{

    public function init()
    {
        $uploadImage = $this->createElement('file', 'uploadImage');
        $uploadImage->setLabel("Wybierz obrazek:")
                ->setDestination(APPLICATION_PATH . '/../public/obrazki')
                ->addValidator('Count', false, 1)
                ->addValidator('Size', false, 102400)
                ->addValidator('Extension', false, 'jpg,png,gif');
      
        $submit = $this->createElement('submit', 'submit');
        $submit->setLabel('Wyslij');
        
        $this->addElements(array(
            $uploadImage,
            $submit
        ));
        $this->setEnctype('multipart/form-data');
        
    }
}


Kod
// File application/controllers/ArticlesController.php
[...]
    public function uploadImageAction()
    {
        
        $uploadForm = new Application_Form_UploadImage();
        $uploadForm->setMethod('post');
        if ( $this->getRequest()->isPost() ) {
            if (!$uploadForm->isValid($_POST)) { // Próba walidacji formularza
                $information = 'Błąd podczas sprawdzania poprawności formularza.';
            } elseif (!$uploadForm->uploadImage->receive()) { // Odbiór pliku
                $information = 'Błąd podczas odbierania pliku.';
            } else {
                $information = 'Plik '.$uploadForm->uploadImage->getFileName(). ' został poprawnie wysłany.';
            }
        }
        $this->view->form = $uploadForm;
        $this->view->information = $information;
    }
[...]


Kod
<?php
// File application/views/scripts/articles/upload-image.phtml
    echo $this->form;
    echo $this->information;
?>
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.