我在前端有一个文件上传表单。
此时,当创建新记录时,文件被上传到
%sf_data_dir%/files/
但是由于一些业务逻辑,我需要将文件上传到
%sf_data_dir%/files/%record_id%/
因此上传的文件应该在记录创建后保存。
我怎么才能做到呢?
如果你使用文件上传,你的表单肯定会使用sfValidatorFile(如果没有,那是错误的):
$this->validatorSchema['image'] = new sfValidatorFile(array(
'required' => true,
'mime_types' => 'web_images',
));
这个验证器返回一个sfValidatedFile实例,可以保存在任何你想要的地方(它比move_uploaded_file更安全,有对目录,文件名…的检查)。
在你的操作中(或者在你想要/需要的表单中),你现在可以这样做:
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form->bind(
$request->getParameter($form->getName()),
$request->getFiles($form->getName())
);
if ($form->isValid())
{
$job = $form->save();
// Saving the file to filesystem
$file = $form->getValue('my_upload_field');
$file->save('/path/to/save/'.$job->getId().'/myimage.'.$file->getExtension());
$this->redirect('job_show', $job);
}
}
不要犹豫,打开sfValidatedFile看看它是如何工作的