【问题标题】:How to create multiple file upload field using symfony form type?如何使用 symfony 表单类型创建多个文件上传字段?
【发布时间】:2019-02-07 06:08:12
【问题描述】:

我已经阅读了文档,但不清楚我们如何使用 symfony formtype 创建以下输入字段。

<input id="image-file" name="files[]" type="file" multiple>

【问题讨论】:

    标签: php symfony symfony-forms


    【解决方案1】:

    试试这样:

    use Symfony\Component\Form\Extension\Core\Type\FileType;
    
    class ImageFile extends AbstractType
    {
        /**
         * @param FormBuilderInterface $builder
         * @param array $options
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('images', FileType::class, [
                    'multiple' => true,
                    'attr'     => [
                        'accept' => 'image/*',
                        'multiple' => 'multiple'
                    ]
                ])
            ;
        }
    }
    

    并将您的“图像”属性更改为“图像”属性:

    /**
     * Set images
     *
     * @param string $images
     *
     * @return satelliteImage[]
     */
    public function setImages($images)
    {
        $this->images = $images;
    
        return $this;
    }
    
    /**
     * Get images
     *
     * @return string
     */
    public function getImages()
    {
        return $this->image;
    }
    
    public function addImage($image)
    {
        $this->images[] = $image;
    
        return $this;
    }
    

    【讨论】:

      【解决方案2】:

      您需要了解上传的概念,并尝试实现 Symfony 形状以让您正确安全地上传文件。 Upload File with Symfony
      这个教程也应该对你有帮助 Upload multiple files with Symfony 4
      对于没有框架的php应该喜欢

      define("UPLOAD_DIR", "/path/to/uploaded_file/");
      
      if (!empty($_FILES["files"])) {
          $myFile = $_FILES["files"];
      
          if ($myFile["error"] !== UPLOAD_ERR_OK) {
              echo "<p>An error occurred.</p>";
              exit;
          }
      
          // ensure a safe filename
          $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
      
          // don't overwrite an existing file
          $i = 0;
          $parts = pathinfo($name);
          while (file_exists(UPLOAD_DIR . $name)) {
              $i++;
              $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
          }
      
          // preserve file from temporary directory
          $success = move_uploaded_file($myFile["tmp_name"],
              UPLOAD_DIR . $name);
          if (!$success) {
              echo "<p>Unable to save file.</p>";
              exit;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-07
        相关资源
        最近更新 更多