Symfony2:如何在没有表单的情况下验证UploadedFile?

5
我需要从URL下载文件并使用Uploadable (DoctrineExtensions)将其保存到我的服务器上。几乎一切都正常,我的方法是:
  1. 使用curl将文件下载到我的服务器的临时文件夹中
  2. 创建UploadedFile方法并填充属性值
  3. 将其插入到可上传实体Media
  4. 进行验证
  5. 持久化和刷新
简化代码:
// ... 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中的Uploadable扩展配置),并保存到数据库。但是使用手动创建的UploadedFile进行验证会返回以下错误:

文件无法上传。

我可以禁用来自URL的验证器,并使用自定义方法验证文件,但使用Symfony Validator对象似乎是更清洁的解决方案。
有没有办法使它工作?
1个回答

3
在Symfony验证组件中,约束UploadedFile内部使用此函数:http://php.net/manual/es/function.is-uploaded-file.php。您可以在此处查看:https://github.com/symfony/HttpFoundation/blob/master/File/UploadedFile.php#L213
/**
 * 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());
}

您需要创建自己的Downloadvalidator(是的,您实际上是使用curl下载文件)


有人能解释一下如何创建这个“downloadvalidator”吗? - ThEBiShOp
@ThEBiShOp 看这里:https://symfony.com/doc/current/validation/custom_constraint.html - Javier Neyra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接