国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

Doctrine文件上傳處理例子

2024-09-04 11:45:12
字體:
來源:轉載
供稿:網友

Doctrine是基于數據庫抽像層上的ORM,它可以通過PHP對象輕松訪問所有的數據庫,例如MYSQL,它支持的PHP最低版本為5.2.3,下面我們一起來看看Doctrine文件上傳處理例子,希望文章對各位有幫助.

基本設置,創建一個簡單的Doctrine實體類:

  1. // src/Acme/DemoBundle/Entity/Document.php 
  2. namespace Acme/DemoBundle/Entity; 
  3.    
  4. use Doctrine/ORM/Mapping as ORM; 
  5. use Symfony/Component/Validator/Constraints as Assert; 
  6.    
  7. /** 
  8.  * @ORM/Entity 
  9.  */ 
  10. class Document 
  11.     /** 
  12.      * @ORM/Id 
  13.      * @ORM/Column(type="integer") 
  14.      * @ORM/GeneratedValue(strategy="AUTO") 
  15.      */ 
  16.     public $id
  17.    
  18.     /** 
  19.      * @ORM/Column(type="string", length=255) 
  20.      * @Assert/NotBlank 
  21.      */ 
  22.     public $name
  23.    
  24.     /** 
  25.      * @ORM/Column(type="string", length=255, nullable=true) 
  26.      */ 
  27.     public $path
  28.    
  29.     public function getAbsolutePath() 
  30.     { 
  31.         return null === $this->path 
  32.             ? null 
  33.             : $this->getUploadRootDir().'/'.$this->path; 
  34.     } 
  35.    
  36.     public function getWebPath() 
  37.     { 
  38.         return null === $this->path 
  39.             ? null 
  40.             : $this->getUploadDir().'/'.$this->path; 
  41.     } 
  42.    
  43.     protected function getUploadRootDir() 
  44.     { 
  45.         // the absolute directory path where uploaded 
  46.         // documents should be saved 
  47.         return __DIR__.'/../../../../web/'.$this->getUploadDir(); 
  48.     } 
  49.    
  50.     protected function getUploadDir() 
  51.     { 
  52.         // get rid of the __DIR__ so it doesn't screw up 
  53.         // when displaying uploaded doc/image in the view. 
  54.         return 'uploads/documents'
  55.     } 

該document實體有一個名稱與文件相關聯,這個path屬性存儲一個文件的相對路徑并且在數據庫中存儲,這個getAbsolutePath()會返回一個絕對路徑,getWebPath()會返回一個web路徑,用于模板加入上傳文件鏈接.

如果你還沒有這樣做的話,你應該閱讀http://symfony.com/doc/current/reference/forms/types/file.html首先了解基本的上傳過程.

如果您使用注釋來驗證規則(如本例所示),請確保你啟用了注釋驗證(見http://symfony.com/doc/current/book/validation.html#book-validation-configuration).

在處理一個實際的文件上傳時,使用一個“虛擬”的file字段,例如,如果你在controller中直接構建一個form,他可能是這樣的.

  1. public function uploadAction() 
  2.     // ... 
  3.    
  4.     $form = $this->createFormBuilder($document
  5.         ->add('name'
  6.         ->add('file'
  7.         ->getForm(); 
  8.    
  9.     // ... 

下一步,創建file這個屬性到你的Document類中并且添加一些驗證規則:

  1. use Symfony/Component/HttpFoundation/File/UploadedFile; 
  2.    
  3. // ... 
  4. class Document 
  5.     /** 
  6.      * @Assert/File(maxSize="6000000") 
  7.      */ 
  8.     private $file
  9.    
  10.     /** 
  11.      * Sets file. 
  12.      * 
  13.      * @param UploadedFile $file 
  14.      */ 
  15.     public function setFile(UploadedFile $file = null) 
  16.     { 
  17.         $this->file = $file
  18.     } 
  19.    
  20.     /** 
  21.      * Get file. 
  22.      * 
  23.      * @return UploadedFile 
  24.      */ 
  25.     public function getFile() 
  26.     { 
  27.         return $this->file; 
  28.     } 
  29. annotations 
  30. Annotations 
  31. // src/Acme/DemoBundle/Entity/Document.php 
  32. namespace Acme/DemoBundle/Entity; 
  33.    
  34. // ... 
  35. use Symfony/Component/Validator/Constraints as Assert; 
  36.    
  37. class Document 
  38.     /** 
  39.      * @Assert/File(maxSize="6000000") 
  40.      */ 
  41.     private $file
  42.    
  43.     // ... 

當你使用File約束,symfony會自動猜測表單字段輸入的是一個文件上傳,這就是當你創建表單(->add(‘file’))時,為什么沒有在表單明確設置為文件上傳的原因.

下面的控制器,告訴您如何處理全部過程:

  1. // ... 
  2. use Acme/DemoBundle/Entity/Document; 
  3. use Sensio/Bundle/FrameworkExtraBundle/Configuration/Template; 
  4. use Symfony/Component/HttpFoundation/Request; 
  5. // ... 
  6.    
  7. /** 
  8.  * @Template() 
  9.  */ 
  10. public function uploadAction(Request $request
  11.     $document = new Document(); 
  12.     $form = $this->createFormBuilder($document
  13.         ->add('name'
  14.         ->add('file'
  15.         ->getForm(); 
  16.    
  17.     $form->handleRequest($request); 
  18.    
  19.     if ($form->isValid()) { 
  20.         $em = $this->getDoctrine()->getManager(); 
  21.    
  22.         $em->persist($document); 
  23.         $em->flush(); 
  24.    
  25.         return $this->redirect($this->generateUrl(...)); 
  26.     } 
  27.    
  28.     return array('form' => $form->createView()); 

以前的controller當提交name自動的存儲Document實體,但是他不會做任何關于文件的事情并且path屬性也將是空白.

處理文件上傳一個簡單的方法就是在entity持久化之前設置相應的path屬性,在某一時刻處理文件上傳時,要調用Document實體類一個upload()方法給path賦值.

  1. if ($form->isValid()) { 
  2.     $em = $this->getDoctrine()->getManager(); 
  3.    
  4.     $document->upload(); 
  5.    
  6.     $em->persist($document); 
  7.     $em->flush(); 
  8.    
  9.     return $this->redirect(...); 

這個upload()方法利用UploadedFile對象,是它提交后返回file字段:

  1. public function upload() 
  2.     // the file property can be empty if the field is not required 
  3.     // 該file屬性為空這個屬性就不需要了 
  4.     if (null === $this->getFile()) { 
  5.         return
  6.     } 
  7.    
  8.     // use the original file name here but you should 
  9.     // sanitize it at least to avoid any security issues 
  10.     //  這里你應該使用原文件名但是應該至少審核它避免一些安全問題 
  11.     // move takes the target directory and then the 
  12.     // target filename to move to 
  13.     // 將目標文件移動到目標目錄 
  14.     $this->getFile()->move( 
  15.         $this->getUploadRootDir(), 
  16.         $this->getFile()->getClientOriginalName() 
  17.     ); 
  18.    
  19.     // set the path property to the filename where you've saved the file 
  20.     // 設置path屬性為你保存文件的文件名 
  21.     $this->path = $this->getFile()->getClientOriginalName(); 
  22.    
  23.     // clean up the file property as you won't need it anymore 
  24.     // 清理你不需要的file屬性 
  25.     $this->file = null; 

使用生命周期回調:

生命周期回調是一種有限的技術,他有一些缺點,如果你想移除Document::getUploadRootDir()方法里的寫死的編碼__DIR__,最好的方法是開始使用Doctrine listeners,在哪里你將能夠注入內核參數,如kernel.root_dir來建立絕對路徑.

這種原理工作,他有一個缺陷:也就是說當entity持久化時會有什么問題呢?答:該文件已經轉移到了它的最終位置,實體類下的path屬性不能夠正確的實體化.

如果entity有持久化問題或者文件不能夠移動,什么事情也沒有發生,為了避免這些問題,你應該改變這種實現方式以便數據庫操作和自動刪除文件:

  1. /** 
  2.  * @ORM/Entity 
  3.  * @ORM/HasLifecycleCallbacks 
  4.  */ 
  5. class Document 

接下來,利用這些回調函數重構Document類:

  1. use Symfony/Component/HttpFoundation/File/UploadedFile; 
  2.    
  3. /** 
  4.  * @ORM/Entity 
  5.  * @ORM/HasLifecycleCallbacks 
  6.  */ 
  7. class Document 
  8.     private $temp
  9.    
  10.     /** 
  11.      * Sets file. 
  12.      * 
  13.      * @param UploadedFile $file 
  14.      */ 
  15.     public function setFile(UploadedFile $file = null) 
  16.     { 
  17.         $this->file = $file
  18.         // check if we have an old image path 
  19.         // 檢查如果我們有一個舊的圖片路徑 
  20.         if (isset($this->path)) { 
  21.             // store the old name to delete after the update 
  22.             $this->temp = $this->path; 
  23.             $this->path = null; 
  24.         } else { 
  25.             $this->path = 'initial'
  26.         } 
  27.     } 
  28.    
  29.     /** 
  30.      * @ORM/PrePersist() 
  31.      * @ORM/PreUpdate() 
  32.      */ 
  33.     public function preUpload() 
  34.     { 
  35.         if (null !== $this->getFile()) { 
  36.             // do whatever you want to generate a unique name 
  37.             // 去生成一個唯一的名稱 
  38.             $filename = sha1(uniqid(mt_rand(), true)); 
  39.             $this->path = $filename.'.'.$this->getFile()->guessExtension(); 
  40.         } 
  41.     } 
  42.    
  43.     /** 
  44.      * @ORM/PostPersist() 
  45.      * @ORM/PostUpdate() 
  46.      */ 
  47.     public function upload() 
  48.     { 
  49.         if (null === $this->getFile()) { 
  50.             return
  51.         } 
  52.    
  53.         // if there is an error when moving the file, an exception will 
  54.         // be automatically thrown by move(). This will properly prevent 
  55.         // the entity from being persisted to the database on error 
  56.         //當移動文件發生錯誤,一個異常move()會自動拋出異常。 
  57.         //這將阻止實體持久化數據庫發生錯誤。 
  58.         $this->getFile()->move($this->getUploadRootDir(), $this->path); 
  59.    
  60.         // check if we have an old image 
  61.         if (isset($this->temp)) { 
  62.             // delete the old image 
  63.             unlink($this->getUploadRootDir().'/'.$this->temp); 
  64.             // clear the temp image path 
  65.             $this->temp = null; 
  66.         } 
  67.         $this->file = null; 
  68.     } 
  69.    
  70.     /** 
  71.      * @ORM/PostRemove() 
  72.      */ 
  73.     public function removeUpload() 
  74.     { 
  75.         $file = $this->getAbsolutePath(); 
  76.         if ($file) { 
  77.             unlink($file); 
  78.         } 
  79.     } 

如果更改你的entity是由Doctrine event listener 或event subscriber處理,這個 preUpdate()回調函數必須通知Doctrine關于正在做的改變,有關preUpdate事件限制的完整參考請查看 http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#preupdate

現在這個類做了你需要的一切:他會在entity持久化之前生成一個唯一的文件名,持久化之后,移動文件,刪除文件.

現在移動文件是entity自動完成,這個$document->upload()就應該從controller中移除了:

  1. if ($form->isValid()) { 
  2.     $em = $this->getDoctrine()->getManager(); 
  3.    
  4.     $em->persist($document); 
  5.     $em->flush(); 
  6.    
  7.     return $this->redirect(...); 

這個@ORM/PrePersist()和@ORM/PostPersist()事件回調:一個是在entity持久化到數據庫之前觸發,一個是在entity持久化到數據庫之后觸發。另一方面, @ORM/PreUpdate() 和 @ORM/PostUpdate()事件回調時當實體更新時觸發。

當改變entity字段后進行持久化操作時,PreUpdate和PostUpdate回調才會被觸發。這意味著,默認情況下,你只改變了$file屬性,這些事件不會被觸發,因為這個屬性它自己不會持久化到Doctrine。有一個解決方法,就是創建一個updated字段把它持久化到Doctrine,并當文件改變時手動調整它。

使用ID作為文件名

如果要使用ID作為文件名,實現略有不同,您需要保存path屬性為文件擴展名,而不是實際的文件名:

  1. use Symfony/Component/HttpFoundation/File/UploadedFile; 
  2.    
  3. /** 
  4.  * @ORM/Entity 
  5.  * @ORM/HasLifecycleCallbacks 
  6.  */ 
  7. class Document 
  8.     private $temp
  9.    
  10.     /** 
  11.      * Sets file. 
  12.      * 
  13.      * @param UploadedFile $file 
  14.      */ 
  15.     public function setFile(UploadedFile $file = null) 
  16.     { 
  17.         $this->file = $file
  18.         // check if we have an old image path 
  19.         if (is_file($this->getAbsolutePath())) { 
  20.             // store the old name to delete after the update 
  21.             $this->temp = $this->getAbsolutePath(); 
  22.         } else { 
  23.             $this->path = 'initial'
  24.         } 
  25.     } 
  26.    
  27.     /** 
  28.      * @ORM/PrePersist() 
  29.      * @ORM/PreUpdate() 
  30.      */ 
  31.     public function preUpload() 
  32.     { 
  33.         if (null !== $this->getFile()) { 
  34.             $this->path = $this->getFile()->guessExtension(); 
  35.         } 
  36.     } 
  37.    
  38.     /** 
  39.      * @ORM/PostPersist() 
  40.      * @ORM/PostUpdate() 
  41.      */ 
  42.     public function upload() 
  43.     { 
  44.         if (null === $this->getFile()) { 
  45.             return
  46.         } 
  47.    
  48.         // check if we have an old image 
  49.         if (isset($this->temp)) { 
  50.             // delete the old image 
  51.             unlink($this->temp); 
  52.             // clear the temp image path 
  53.             $this->temp = null; 
  54.         } 
  55.    
  56.         // you must throw an exception here if the file cannot be moved 
  57.         // so that the entity is not persisted to the database 
  58.         // which the UploadedFile move() method does 
  59.         $this->getFile()->move( 
  60.             $this->getUploadRootDir(), 
  61.             $this->id.'.'.$this->getFile()->guessExtension() 
  62.         ); 
  63.    
  64.         $this->setFile(null); 
  65.     } 
  66.    
  67.     /** 
  68.      * @ORM/PreRemove() 
  69.      */ 
  70.     public function storeFilenameForRemove() 
  71.     { 
  72.         $this->temp = $this->getAbsolutePath(); 
  73.     } 
  74.    
  75.     /** 
  76.      * @ORM/PostRemove() 
  77.      */ 
  78.     public function removeUpload() 
  79.     {  //Vevb.com 
  80.         if (isset($this->temp)) { 
  81.             unlink($this->temp); 
  82.         } 
  83.     } 
  84.    
  85.     public function getAbsolutePath() 
  86.     { 
  87.         return null === $this->path 
  88.             ? null 
  89.             : $this->getUploadRootDir().'/'.$this->id.'.'.$this->path; 
  90.     } 

你會注意到,在這種情況下,你需要做一點工作,以刪除該文件,在數據刪除之前,你必須保存文件路徑(因為它依賴于ID),然后,一旦對象已經完全從數據庫中刪除,你就可以安全的刪除文件(在數據刪除之后).

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 巨野县| 新源县| 贵州省| 固镇县| 天祝| 桓仁| 兴国县| 永修县| 留坝县| 深州市| 桃源县| 申扎县| 沙坪坝区| 鸡泽县| 铁岭县| 鲜城| 海门市| 奉贤区| 绍兴县| 东至县| 潜山县| 恭城| 耿马| 泉州市| 宁安市| 吴忠市| 长顺县| 宁国市| 峨山| 信宜市| 兴城市| 高淳县| 铁岭县| 民和| 永德县| 永修县| 于田县| 丰县| 云南省| 蕉岭县| 丹江口市|