这是我的路线:
'router' => array(
'routes' => array(
'upload' => array(
'type' => 'segment',
'options' => array(
'route' => '/products/upload[/:products]',
'defaults' => array(
'controller' => 'Products\Controller\Upload',
'action' => 'index'
),
),
'may_terminate' => true,
'child_routes' => array(
'uploadsuccessful' => array(
'type' => 'literal',
'options' => array(
'route' => '/uploadsuccessful',
'defaults' => array(
'controller' => 'Products\Controller\Upload',
'action' => 'successful'
),
),
),
),
),
),
);
我试图从不同的视图脚本中多次调用此路由,从而提供不同的[/:products]
参数。
<a href="<?php echo $this->url('upload', array('products' =>'shoes')); ?>">Upload Shoes Product Image</a>
<a href="<?php echo $this->url('upload', array('products' =>'trainers')); ?>">Upload Trainers Product Image</a>
<a href="<?php echo $this->url('upload', array('products' =>'hats')); ?>">Upload Hat Product Image</a>
这是我的控制器代码。
<?php
namespace Products\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Products\Form\UploadForm;
class UploadController extends AbstractActionController
{
protected $_dir = null;
public function indexAction()
{
$products = $this->params()->fromRoute('products');
$config = $this->getServiceLocator()->get('Config');
$fileManagerDir =$config['file_manager']['dir'];
$this->_dir = realpath($fileManagerDir) .
DIRECTORY_SEPARATOR .
$products;
if (!is_dir($this->_dir)) {
//read, write, execute
mkdir($this->_dir, 0777);
}
$form = new UploadForm($this->_dir, 'upload-form');
$request = $this->getRequest();
if ($request->isPost()) {
$post = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid()) {
$data = $form->getData();
$this->setFileNames($data);
return $this->redirect()->toRoute('upload/uploadsuccessful', array('products' =>$products));
}
}
return new ViewModel(array('form' => $form));
}
public function successfulAction()
{
$file = array();
$flashMessenger = $this->flashMessenger();
if ($flashMessenger->hasMessages()) {
foreach($flashMessenger->getMessages() as $key => $value) {
$file = $value;
}
}
return new ViewModel(array('file' => $file));
}
protected function setFileNames($data)
{
unset($data['submit']);
foreach ($data['image-file'] as $key => $file) {
rename($file['tmp_name'], $this->_dir . DIRECTORY_SEPARATOR . $file['name']);
}
}
}
我认为这个想法很明确:对于每个[/:products]
参数,我尝试在$fileManagerDir
中创建具有给定名称的单独文件夹。
但是,有一个问题。当我点击按钮上传($request->isPost() == true)
参数$products
变为null
时,上传的文件就不会转到相应的文件夹。此外,我无法重定向到成功的操作 - 错误出现&#34;缺少参数&#34;因为$ products为null。
答案 0 :(得分:0)
在您的视图脚本中,上传按钮是href链接。这将导致GET REQUEST被发送到控制器而不是POST,也不会出现FILES。除非是这样,否则你正在用外部JS拦截click事件,你在这里没有提到。路径网址应位于表单操作属性中。提交按钮应该是按钮而不是链接(除非您使用的是JS,此处未提及)。确保将表单方法设置为POST。
类似的东西:
<form action="<?php echo $this->url('upload', array('products' =>'shoes')); ?>" method="post" enctype="multipart/form-data">
您需要使用JS处理动态操作或重新设计路由。