doucheng9304 2014-11-17 17:53
浏览 111

上传图片,将“filename”列设置为正在上传的文件的名称?

I'm using Sonata Admin bundle and basically, when a user uploads an image for the carousel ( I have an upload widget ) I want the "filename" column of my table to be automatically filled in with the filenames name. So if its, "image_001.jpg" I want the filename column to automatically say "image_001.jpg" once the file has been uploaded. How would I go about achieving this ?

Also if you have any tips of whether theres anything better I could do that would be great! I feel like my table should have a url column as well but I'm not sure as images for the carousel will always be uploaded to the path in the code below.

Here's my YAML file:

Example\CmsBundle\Entity\Carousel:
   type: entity
   table: carousel
   id:
      id:
         type: integer
         generator: { strategy: AUTO }
   fields:
      filename:
         type: string
         length: 100
      updated:
         type: datetime
         nullable: true
   lifecycleCallbacks:
      prePersist: [ lifecycleFileUpload ]
      preUpdate:  [ lifecycleFileUpload ]

My entity file:

/**
 * Carousel
 */
class Carousel
{

const SERVER_PATH_TO_IMAGE_FOLDER = 'bundles/examplecompany/images/carousel';

    /**
     * @var integer
     */
    private $id;

    /**
     * @var stringß
     */
    private $filename;

    /**
     * @var \DateTime
     */
    private $updated;

    /**
     * Unmapped property to handle file uploads
     */
    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;
    }

    /**
     * Manages the copying of the file to the relevant place on the server
     */
    public function upload()
    {
        // the file property can be empty if the field is not required
        if (null === $this->getFile()) {
            return;
        }

        // we use the original file name here but you should
        // sanitize it at least to avoid any security issues

        // move takes the target directory and target filename as params
        $this->getFile()->move(
            Carousel::SERVER_PATH_TO_IMAGE_FOLDER,
            $this->getFile()->getClientOriginalName()
        );

        // set the path property to the filename where you've saved the file
        $this->filename = $this->getFile()->getClientOriginalName();

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

    /**
     * Lifecycle callback to upload the file to the server
     */
    public function lifecycleFileUpload() {
        $this->upload();
    }

    /**
     * Updates the hash value to force the preUpdate and postUpdate events to fire
     */
    public function refreshUpdated() {
        $this->setUpdated(new \DateTime("now"));
    }

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

    /**
     * Set filename
     *
     * @param string $filename
     * @return Carousel
     */
    public function setFilename($filename)
    {
        $this->filename = $filename;

        return $this;
    }

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

    /**
     * Set updated
     *
     * @param \DateTime $updated
     * @return Carousel
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get updated
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }
    /**
     * @ORM\PrePersist
     */
    /*public function lifecycleFileUpload()
    {
        // Add your code here
    }*/
}

EDIT:

Carousel Admin Code:

class CarouselAdmin extends Admin
{

   // setup the default sort column and order
   protected $datagridValues = array(
      '_sort_order' => 'ASC',
      '_sort_by' => 'updated_at'
   );

   protected function configureFormFields(FormMapper $formMapper)
   {
      $formMapper
         ->add('file', 'file', array('required' => false))
         ->add('filename')
         ->add('text_block')
      ;
   }

   protected function configureDatagridFilters(DatagridMapper $datagridMapper)
   {
      $datagridMapper
         ->add('filename')
         ->add('updated_at')
      ;
   }

   protected function configureListFields(ListMapper $listMapper)
   {
      $listMapper
         ->add('')
         ->addIdentifier('filename')
         ->add('text_block')
         ->add('updated_at')
         // add custom action links
         ->add('_action', 'actions', array(
             'actions' => array(
                 'edit' => array(),
                 'delete' => array(),
             )
         ))
      ;
   }

   protected function configureRoutes(RouteCollection $collection)
    {
      // remove the "Add New" button
      //$collection->remove('create');

    }

   public function prePersist($image) {
      $this->manageFileUpload($image);
   }

   public function preUpdate($image) {
      $this->manageFileUpload($image);
   }

   private function manageFileUpload($image) {
      if ($image->getFile()) {
         $image->refreshUpdated();
      }
   }

}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?