php Zend 框架:图片上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1868143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Zend Framework: image upload
提问by Erik
I want to upload an image with Zend Framework version 1.9.6. The uploading itself works fine, but I want a couple of other things as well ... and I'm completely stuck.
我想使用 Zend Framework 1.9.6 版上传图像。上传本身工作正常,但我还想要一些其他的东西......我完全被卡住了。
- Error messages for failing to upload an image won't show up.
- If a user doesn't enter all the required fields but has uploaded an image then I want to display the uploaded image in my form. Either as an image or as a link to the image. Just some form of feedback to the user.
- I want to use Zend_ Validate_ File_ IsImage. But it doesn't seem to do anything.
- And lastly; is there some automatic renaming functionality?
- 无法上传图像的错误消息不会显示。
- 如果用户没有输入所有必填字段但已上传图像,那么我想在表单中显示上传的图像。无论是作为图像还是作为图像的链接。只是对用户的某种形式的反馈。
- 我想使用 Zend_Validate_File_IsImage。但它似乎没有任何作用。
- 最后; 是否有一些自动重命名功能?
All ideas and suggestions are very welcome. I've been struggling for two days now.
非常欢迎所有的想法和建议。我已经挣扎了两天了。
These are simplified code snippets:
这些是简化的代码片段:
myform.ini
配置文件
method = "post"
elements.title.type = "text"
elements.title.options.label = "Title"
elements.title.options.attribs.size = 40
elements.title.options.required = true
elements.image.type = "file"
elements.image.options.label = "Image"
elements.image.options.validators.isimage.validator = "IsImage"
elements.submit.type = "submit"
elements.submit.options.label = "Save"
TestController
测试控制器
<?php
class Admin_TestController extends Zend_Controller_Action
{
public function testAction ()
{
$config = new Zend_Config_Ini(MY_SECRET_PATH . 'myform.ini');
$f = new Zend_Form($config);
if ($this->_request->isPost())
{
$data = $this->_request->getPost();
$imageElement = $f->getElement('image');
$imageElement->receive();
//$imageElement->getValue();
if ($f->isValid($data))
{
//save data
$this->_redirect('/admin');
}
else
{
$f->populate($data);
}
}
$this->view->form = $f;
}
}
?>
My view just echo's the 'form' variable.
我的观点只是 echo 是 'form' 变量。
回答by lo_fye
First, put this at the start of your script:
首先,将其放在脚本的开头:
error_reporting(E_ALL);//this should show all php errors
error_reporting(E_ALL);//这应该显示所有的php错误
I think the error messages are missing from the form because you re-populate the form before you display it. I think that wipes out any error messages. To fix that, remove this part:
我认为表单中缺少错误消息,因为您在显示之前重新填充了表单。我认为这会消除任何错误消息。要解决此问题,请删除此部分:
else
{
$f->populate($data);
}
To show the uploaded image in the form, just add a div to your view template, like this:
要在表单中显示上传的图像,只需在视图模板中添加一个 div,如下所示:
<div style="float:right"><?=$this->image?></div>
If the image uploaded ok, then populate $view->image with an img tag.
如果图像上传正常,则使用 img 标签填充 $view->image。
As for automatic re-naming, no, it's not built in, but it's very easy. I'll show you how below. Here's how I handle my image uploads:
至于自动重命名,不,它不是内置的,但很容易。我会告诉你如何在下面。以下是我处理图片上传的方式:
$form = new Zend_Form();
$form->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
$image = new Zend_Form_Element_File('image');
$image->setLabel('Upload an image:')
->setDestination($config->paths->upload)
->setRequired(true)
->setMaxFileSize(10240000) // limits the filesize on the client side
->setDescription('Click Browse and click on the image file you would like to upload');
$image->addValidator('Count', false, 1); // ensure only 1 file
$image->addValidator('Size', false, 10240000); // limit to 10 meg
$image->addValidator('Extension', false, 'jpg,jpeg,png,gif');// only JPEG, PNG, and GIFs
$form->addElement($image);
$this->view->form = $form;
if($this->getRequest()->isPost())
{
if(!$form->isValid($this->getRequest()->getParams()))
{
return $this->render('add');
}
if(!$form->image->receive())
{
$this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
return $this->render('add');
}
if($form->image->isUploaded())
{
$values = $form->getValues();
$source = $form->image->getFileName();
//to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to.
$new_image_name = 'someNameYouInvent';
//save image to database and filesystem here
$image_saved = move_uploaded_file($source, '/www/yoursite/images/'.$new_image_name);
if($image_saved)
{
$this->view->image = '<img src="/images/'.$new_image_name.'" />';
$form->reset();//only do this if it saved ok and you want to re-display the fresh empty form
}
}
}
回答by Hyman Tanner
First, have a look at the Quick Starttutorial. Note how it has an ErrorController.php that will display error messages for you. Also note how the application.ini has these lines to cause PHP to emit error messages, but make sure you're in the "development" environment to see them (which is set in public/.htaccess).
首先,看看快速入门教程。注意它是如何有一个 ErrorController.php 来为你显示错误消息的。还要注意 application.ini 的这些行是如何导致 PHP 发出错误消息的,但要确保您在“开发”环境中才能看到它们(在 public/.htaccess 中设置)。
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
Second, ZF has a renaming filter for file uploads:
其次,ZF 有一个用于文件上传的重命名过滤器:
$upload_elt = new Zend_Form_Element_File('upload');
$upload_elt
->setRequired(true)
->setLabel('Select the file to upload:')
->setDestination($uploadDir)
->addValidator('Count', false, 1) // ensure only 1 file
->addValidator('Size', false, 2097152) // limit to 2MB
->addValidator('Extension', false, 'doc,txt')
->addValidator('MimeType', false,
array('application/msword',
'text/plain'))
->addFilter('Rename', implode('_',
array($this->_user_id,
$this->_upload_category,
date('YmdHis'))))
->addValidator('NotExists', false, $uploadDir)
;
Some of the interesting things above:
上面的一些有趣的事情:
- mark the upload as required (which your .ini doesn't seem to do)
- put all the uploads in a special directory
- limit file size and acceptable mime types
- rename upload to myuser_category_timestamp
- don't overwrite an existing file (unlikely, given our timestamp scheme, but let's make sure anyway)
- 将上传标记为需要(您的 .ini 似乎没有这样做)
- 将所有上传的内容放在一个特殊目录中
- 限制文件大小和可接受的 MIME 类型
- 将上传重命名为 myuser_category_timestamp
- 不要覆盖现有文件(不太可能,鉴于我们的时间戳方案,但无论如何让我们确保)
So, the above goes in your form. In the controller/action that receives the upload, you could do this:
因此,以上内容以您的形式出现。在接收上传的控制器/操作中,您可以执行以下操作:
$original_filename = $form->upload->getFileName(null, false);
if ($form->upload->receive()) {
$model->saveUpload(
$this->_identity, $form->upload->getFileName(null, false),
$original_filename
);
}
Note how we capture the $original_filename (if you need it) before doing receive(). After we receive(), we do getFileName() to get the thing that the rename filter picked as the new filename.
请注意我们如何在执行 receive() 之前捕获 $original_filename(如果需要)。在我们接收()之后,我们执行 getFileName() 以获取重命名过滤器选择的内容作为新文件名。
Finally, in the model->saveUpload method you could store whatever stuff to your database.
最后,在 model->saveUpload 方法中,您可以将任何内容存储到数据库中。
回答by Jakob Alexander Eichler
When following lo_fye's listing I experienced problems with custom decorators. I do not have the default File Decorator set and got the following exception:
在关注 lo_fye 的列表时,我遇到了自定义装饰器的问题。我没有设置默认的文件装饰器并得到以下异常:
Warning: Exception caught by form: No file decorator found... unable to render file element Stack Trace:
The Answer to this is that one of your decrators must implement the empty interface Zend_Form_Decorator_Marker_File_Interface
对此的答案是您的装饰者之一必须实现空接口 Zend_Form_Decorator_Marker_File_Interface
回答by Joris Kok
Also sometimes it happens to bug when using an ajax request. Try it without an ajax request and don't forget the multipart form.
此外,有时在使用 ajax 请求时会发生错误。在没有 ajax 请求的情况下尝试它,不要忘记多部分表单。
回答by Don
Make sure your view also outputs any error messages that you generate in the controller: loading errors, field validation, file validation. Renaming would be your job, as would other post processing such as by image-magick convert.
确保您的视图还输出您在控制器中生成的任何错误消息:加载错误、字段验证、文件验证。重命名将是您的工作,其他后期处理(例如通过图像魔术转换)也是如此。

