【问题标题】:Symfony - The file could not be foundSymfony - 找不到文件
【发布时间】:2015-04-30 16:56:11
【问题描述】:

实体有 nullable=true。表格有要求=假。生成的 HTML 没有任何要求。

当我离开文件输入时出现错误:

找不到文件。

老实说,我不知道我应该去哪里寻找... ;)

public function updateAction(Request $request, $id)
{

    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('FortiCoreBundle:Article')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Article entity.');
    }

    $deleteForm = $this->createDeleteForm($id);
    $editForm = $this->createEditForm($entity);
    $editForm->handleRequest($request);
    // $editForm->isVail() false because have error The file could not be found.
    if ($editForm->isValid()) {

实体文件:

/**
 * @var string
 *
 * @ORM\Column(name="path", type="string", length=255, nullable=true)
 * @Gedmo\UploadableFilePath
 */
private $path;

/**
 * @var string
 *
 * @Assert\File(
 *     maxSize="3M",
 *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
 * )
 *
 * @ORM\Column(name="filename", type="string", nullable=true)
 * @Gedmo\UploadableFileName
 */
private $filename;

public function uploadPath()
{
    return 'images/article/' . date('Y') . '/' . date('m');
}

public function getRelativePath()
{
    if (empty($this->filename)) {
        return null;
    } else {
        return $this->uploadPath() . '/' . $this->filename;
    }
}

/**
 * Set filename
 *
 * @param string $filename
 * @return Article
 */
public function setFilename($filename)
{
    if (!is_null($filename)) {
        $this->filename = $filename;
    }

    return $this;
}

/**
 * Get filename
 *
 * @return string
 */
public function getFilename()
{
    return $this->filename;
}

和FormType文件:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        //...
        ->add('filename', 'file', array(
            'label' => 'Zdjęcie',
            'required' => false,
            'data_class' => null,
            'attr' => array(
                "class" => 'no-border btn-xs')
        ))
        //...
    ;
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Forti\CoreBundle\Entity\Article'
    ));
}

public function getName()
{
    return 'forti_corebundle_articletype';
}

【问题讨论】:

  • 重要评论:我可以使用空文件输入创建新实体。

标签: file symfony upload file-not-found


【解决方案1】:

我知道我迟到了,但解决我的问题是我在 form 中缺少以下内容

enctype="multipart/form-data"

 <form method="post" action="{{ path('your_route_name') }}" novalidate enctype="multipart/form-data">

【讨论】:

    【解决方案2】:

    您应该为文件上传字段和文件路径存储使用不同的类属性。所以一个处理文件字段(@Assert..)和一个将路径存储在数据库中(@ORM...)

    来自documentation

    要处理表单中的实际文件上传,请使用“虚拟”文件字段。

    如果您仍有问题,请尝试不使用 Gedmo 扩展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 2021-10-08
      相关资源
      最近更新 更多