drf16571 2017-01-13 16:12
浏览 44
已采纳

如何从PHP表单获取uploadedFile数组

I am new to PHP. I succeeded in uploading single image to a form and saving it in the database. But when I modify that to upload multiple images, I get an error saying

The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) array.

class SatelliteImages
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;



/**
 *  @var array
 */
    private $files= array();


    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     *Set files
     *
     * @param UploadedFile[] $files
     */
    public function setFiles($files)
    {
        $this->files = $files;

        //return $this;
    }

    /**
     * Get files
     *
     * @return UploadedFile[]
     */
    public function getFiles()
    {
        return $this->files;
    }

    /**
     * @param satelliteImage[] $images
     *
     * @return satelliteImage[]
     *
     */
    public function upload($images){
        foreach ($this->getFiles() as $key => $file) {
            $images[$key]->setImage(file_get_contents($file));
        }
        return $images;
    }
}

This is the SatelliteImage entity(single image)

    class satelliteImage
    {
        /**
         * @var int
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;

        /**
         * @var float
         *
         * @ORM\Column(name="latitude", type="float")
         */
        private $latitude;

        /**
         * @var float
         *
         * @ORM\Column(name="longitude", type="float")
         */
        private $longitude;

        /**
         * @var string
         *
         * @ORM\Column(name="image", type="blob", nullable=true))
         */
        private $image;

        /**
         * @ORM\Column(type="string", length=255, nullable=true)
         */
        public $path;


        /**
         * Get id
         *
         * @return int
         */
        public function getId()
        {
            return $this->id;
        }

        /**
         * Set latitude
         *
         * @param float $latitude
         *
         * @return satelliteImage
         */
        public function setLatitude($latitude)
        {
            $this->latitude = $latitude;

            return $this;
        }

        /**
         * Get latitude
         *
         * @return float
         */
        public function getLatitude()
        {
            return $this->latitude;
        }

        /**
         * Set longitude
         *
         * @param float $longitude
         *
         * @return satelliteImage
         */
        public function setLongitude($longitude)
        {
            $this->longitude = $longitude;

            return $this;
        }

        /**
         * Get longitude
         *
         * @return float
         */
        public function getLongitude()
        {
            return $this->longitude;
        }

        /**
         * Set image
         *
         * @param string $image
         *
         * @return satelliteImage
         */
        public function setImage($image)
        {
            $this->image = $image;

            return $this;
        }

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

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


        public function getAbsolutePath()
        {
            return null === $this->path
                ? null
                : $this->getUploadRootDir().'/'.$this->path;
        }

        public function getWebPath()
        {
            return null === $this->path
                ? null
                : $this->getUploadDir().'/'.$this->path;
        }

        protected function getUploadRootDir()
        {
            // the absolute directory path where uploaded
            // documents should be saved
            return __DIR__.'/../../../../web/'.$this->getUploadDir();
        }

        protected function getUploadDir()
        {
            // get rid of the __DIR__ so it doesn't screw up
            // when displaying uploaded doc/image in the view.
            return 'uploads/documents';
        }

        /**
         * @Assert\File(maxSize="6000000")
         */
        private $file;

        /**
         * Sets file.
         *
         * @param UploadedFile $file
         */
        public function setFile(UploadedFile $file = null)
        {
            $this->file = $file;
        }

        /**
         * Get file.
         *
         * @return UploadedFile
         */
        public function getFile()
        {
            return $this->file;
        }


        public function upload()
        {
        // the file property can be empty if the field is not required
        if (null === $this->getFile()) {
            return;
        }

        $imgFile=$this->getFile();
        $this->setImage(file_get_contents($imgFile)); 

        // clean up the file property as you won't need it anymore
        $this->file = null;
        }
    }

In my controller, how can I create an array of images and pass it to the above function?

/**
     * @Route("/uploads", name="upload_images")
     *
     */
    public function uploadImages(Request $request)
    {
        $images=new Images();

        $form = $this->createForm(ImageFile::class, $images);
        $form->handleRequest($request);

        $em=$this->getDoctrine()->getManager();
        $images->upload(????);
    }

ImageFile class:

class ImageFile extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('files', FileType::class, array(
                'attr' => array(
                    'accept' => 'image/*',
                    'multiple' => 'multiple'
                )
            ))
            ->add('save',SubmitType::class,array('label'=>'Insert Image','attr'=>array('class'=>'btn btn-primary','style'=>'margin-bottom:15px')))
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => SatelliteImages::class
        ));
    }
}
  • 写回答

2条回答 默认 最新

  • dqy006150 2017-01-14 07:44
    关注

    SOLUTION

    I managed to resolve previous issue by changing 'FileType' to 'CollectionType' in imageFile class's buildForm() function

    public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('files', CollectionType::class, array(
                    'attr' => array(
                        'accept' => 'image/*',
                        'multiple' => 'multiple'
                    )
                ))
                ->add('save',SubmitType::class,array('label'=>'Insert Image','attr'=>array('class'=>'btn btn-primary','style'=>'margin-bottom:15px')))
            ;
        }
    

    I also changed the 'files' like this

    /**
         *  @var array
         */
        private $files;
    
        public function __construct()
        {
            $this->files = new ArrayCollection();
        }
    

    However, when I do that, the 'browse images' button disappears from the view. Any suggestions to fix that?

    I also tried removing the construct() function. When I do that, it gives me an error in the controller saying "invalid argument supplied for foreach"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘