Validation Symfony2:如何验证没有表单的上传文件?
我需要上传下载文件从URL到我的服务器,并坚持它与。几乎一切都很好,我的方法是:Validation Symfony2:如何验证没有表单的上传文件?,validation,symfony,doctrine-extensions,doctrine-uploadable,Validation,Symfony,Doctrine Extensions,Doctrine Uploadable,我需要上传下载文件从URL到我的服务器,并坚持它与。几乎一切都很好,我的方法是: 将带有curl的文件下载到我的服务器上的临时文件夹 创建UploadedFile方法并用属性值填充它 将其插入可上载实体媒体 验证 持之以恒 简化代码: // ... download file with curl // Create UploadedFile object $fileInfo = new File($tpath); $file = new UploadedFile($tpath, basenam
curl
的文件下载到我的服务器上的临时文件夹UploadedFile
方法并用属性值填充它媒体
// ... download file with curl
// Create UploadedFile object
$fileInfo = new File($tpath);
$file = new UploadedFile($tpath, basename($url), $fileInfo->getMimeType(), $fileInfo->getSize(), null);
// Insert file to Media entity
$media = new Media();
$media = $media->setFile($file);
$uploadableManager->markEntityToUpload($media, $file);
// Validate file (by annotations in entity)
$errors = $validator->validate($media);
// If no errors, persist and flush
if(empty($errors)) {
$em->persist($this->parentEntity);
$em->flush();
}
如果我跳过验证,一切正常。文件成功地移动到正确的路径(由config.yml中的可上载扩展名配置)并持久化到数据库。但是使用手动创建的上载文件进行验证时返回此错误:
无法上载该文件
我可以禁用从URL上传的验证程序,并使用自定义方法验证文件,但使用Symfony Validator对象进行验证对我来说似乎是一个更干净的解决方案
有什么方法可以让它工作吗?在symfony验证组件中,约束上载文件在内部使用此函数
你可以在这里看到
您必须创建自己的Downloadvalidator(是的,您实际上是用curl下载文件)有人能解释一下如何创建这个“Downloadvalidator”吗?@ThEBiShOp看这里:
/**
* Returns whether the file was uploaded successfully.
*
* @return bool True if the file has been uploaded with HTTP and no error occurred.
*
* @api
*/
public function isValid()
{
$isOk = $this->error === UPLOAD_ERR_OK;
return $this->test ? $isOk : $isOk && is_uploaded_file($this->getPathname());
}