如何将 $_FILE 和 $_POST 数据传递到表单中?
-
12-12-2019 - |
题
到目前为止,这就是我所知道的将数据从帖子传递到表单的方法。
$form->setData( $this->getRequest()->getPost() );
我认为这可能有用
$form
->setData( $this->getRequest()->getPost() )
->setData( $this->getRequest()->getFiles() );
但事实并非如此。查看框架源代码我确认它不应该。所以我正在考虑将文件数据合并到后期数据中。这肯定不是理想的解决方案吗?getPost() 和 getFiles() 并不返回易于合并的数组,它们返回 Parameter 对象。
请注意,这是 Zend Framework 2 特定的。
解决方案
你有没有尝试过 getFileInfo
现在知道或注意您使用 Zend 的事实。通常以每个文件为基础 $_FILE
是一个基于正在上传的文件信息的数组。文件名、扩展名等。赞兹 getFileInfo
以类似的方式输出该信息。虽然我已经有一段时间没有玩过它了,但还是值得研究一下
示例概念(我知道更多用于多个文件上传,但可以使用一个很好的概念,以防万一您想添加第二个或更多文件)
$uploads = new Zend_File_Transfer_Adapter_Http();
$files = $uploads->getFileInfo();
foreach($files as $file => $fileInfo) {
if ($uploads->isUploaded($file)) {
if ($uploads->isValid($file)) {
if ($uploads->receive($file)) {
$info = $uploads->getFileInfo($file);
$tmp = $info[$file]['tmp_name'];
$data = file_get_contents($tmp);
// here $tmp is the location of the uploaded file on the server
// var_dump($info); to see all the fields you can use
}
}
}
}
其他提示
尝试使用Zend的文件传输适配器,我在控制器中使用了解决方法。我认为表单类中的setData()应将项目合并到数据中而不是替换它们。(imho)
protected function getPostedData()
{
if ( is_null($this->postedData) )
{
$this->postedData = array_merge(
(array) $this->getRequest()->getPost(),
(array) $this->getRequest()->getFiles()
);
}
return $this->postedData;
}
. 我正在使用 array_merge :
$form = $this->getForm('my_form');
$request = $this->getRequest();
if($request->isPost())
{
$file = $this->params()->fromFiles('name_of_file');
$form->setData(array_merge(
$request->getPost()->toArray(),
array('arquivo' => $file['name'])
));
if ($form->isValid()) {
// now i can validate the form field
. 我使用像这个文章解释了创建变量,然后将它们作为每个表单条目的值呼出。
// create array of GET/POST variables then convert each variable to a local variable
$fields = array_keys($_REQUEST);
foreach ($fields as $field) {
$$field = $_REQUEST[$field];
}
. 不隶属于 StackOverflow