上一章我们进行了CRUD的操作,很快速的实现了增删改查,是不是很简单呀。本章我们继续完善,增加上传功能以实现照片和简历的上传,为了适应上传的需求我们要调整一些东西,不要被调整的东西搞混乱呀,一定要认真阅读,很容易的哦!
第一步,为了适应上传的需要,我们要调整file和path字段,并调整相关联的变量名称和代码:
打开src\Nlc\InformationBundle\Entity\Employee.php,把以下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
//src\Nlc\InformationBundle\Entity\Employee.php ... /** * @var string * * @ORM\Column(name="photo", type="string", length=255) */ private $photo; /** * @var string * * @ORM\Column(name="file", type="string", length=255) */ private $file; /** * Set photo * * @param string $photo * @return Employee */ public function setPhoto($photo) { $this->photo = $photo; return $this; } /** * Get photo * * @return string */ public function getPhoto() { return $this->photo; } /** * Set file * * @param string $file * @return Employee */ public function setFile($file) { $this->file= $file; return $this; } /** * Get file * * @return string */ public function getFile() { return $this->file; } ... |
替换成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
/** * @var string * * @ORM\Column(name="photopath", type="string", length=255) */ private $photopath; /** * @var string * * @ORM\Column(name="jlpath", type="string", length=255) */ private $jlpath; /** * Set photopath * * @param string $photopath * @return Employee */ public function setPhotopath($photopath) { $this->photopath = $photopath; return $this; } /** * Get photopath * * @return string */ public function getPhotopath() { return $this->photopath; } /** * Set jlpath * * @param string $jlpath * @return Employee */ public function setJlpath($jlpath) { $this->jlpath = $jlpath; return $this; } /** * Get Jlpath * * @return string */ public function getJlpath() { return $this->jlpath; } |
也就是说我们把原来的$photo替换成了$photopath,目的是来存储上传文件的路径到数据库。
第二步,在Doctrine中处理上传
在Doctrine处理文件上传整体思路是:(注意:具体操作和整体思路不是一一对应的)
- 表单提交(附件提交)
- 在入库或修改之前,获取上传文件信息并将路径信息入库(在PrePersist和PreUpdate事件中操作)
- 入库后将上传的文件移动到相应的路径完成上传步骤(在PostPersist和PostUpdate事件中操作)
- 删除信息时,本地附件也相应的清除(在PostRemove事件中操作)
下面我们一点一点操作:
1)首先添加photofile变量(获取上传的照片信息)和jlfile变量(获取上传的简历信息),并分别添加set和get方法,它的set和get方法和之前自动生成的略有不同,一定要注意。下面我们介绍不同在哪里?因为我们要获取上传文件的信息,在symfony2中方法是Entity中引入:
1 2 3 4 |
namespace Nlc\InformationBundle\Entity; .... use Symfony\Component\HttpFoundation\File\UploadedFile; .... |
并在set和get中使用它来获取上传文件的信息,来看看新的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
//src\Nlc\InformationBundle\Entity\Employee.php namespace Nlc\InformationBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\HttpFoundation\File\UploadedFile; /** * Employee * * @ORM\Table(name="employeetable") * @ORM\Entity(repositoryClass="Nlc\InformationBundle\Entity\EmployeeRepository") */ class Employee { /** * @Assert\File(maxSize="6000000") */ private $photofile; /** * @Assert\File(maxSize="6000000") */ private $jlfile; /** * Sets photofile. * * @param UploadedFile $photofile */ public function setPhotofile(UploadedFile $photofile = null) { $this->photofile = $photofile; } /** * Get photofile. * * @return UploadedFile */ public function getPhotofile() { return $this->photofile; } /** * Sets jlfile. * * @param UploadedFile $jlfile */ public function setJlfile(UploadedFile $jlfile = null) { $this->jlfile = $jlfile; } /** * Get jlfile. * * @return UploadedFile */ public function getJlfile() { return $this->jlfile; } |
以上还加了一些验证,来控制文件上传大小。
2)修改src\Nlc\InformationBundle\Form\EmployeeType.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ->add('age') ->add('sex') ->add('education') ->add('photofile') ->add('jlfile') ->add('createtime') ->add('updatetime') ->add('category') ; } |
让表单能够正常显示上传控件。
3)创建文件的唯一名称
添加一个唯一的编码,来重命名上传的文件和图片让他们有一个唯一的名称避免重复。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
//src\Nlc\InformationBundle\Entity\Employee.php namespace Nlc\InformationBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\HttpFoundation\File\UploadedFile; /** * Employee * * @ORM\Table(name="employeetable") * @ORM\Entity(repositoryClass="Nlc\InformationBundle\Entity\EmployeeRepository") */ class Employee { .... private $photouniqid; private $jlfileuniqid; .... |
以上photouniqid(照片唯一名称)和jlfileuniqid(简历文件的唯一名称)不用创建get和set。
4)创建文件上传的相关路径
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
//src\Nlc\InformationBundle\Entity\Employee.php protected function getRootDir() { // the absolute directory path where uploaded // documents should be saved return __DIR__.'/../../../../web/'; } protected function getUploadRootDir() { // the absolute directory path where uploaded // documents should be saved return $this->getRootDir().$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'; } |
getRootDir()方法:获取web目录在硬盘上的路径,getUploadDir()方法:设置文件上传的相对路径。getUploadRootDir()方法:getRootDir()和getUploadDir()相加获得完整的上传路径;
5)添加唯一命名标识后,我们要添加重要的部分了HasLifecycleCallbacks来触发PrePersist、PreUpdate、PostPersist、PostUpdate、PostRemove。
1 2 3 4 5 6 7 8 9 10 11 12 |
..... /** * Employee * * @ORM\Table(name="employeetable") * @ORM\Entity(repositoryClass="Nlc\InformationBundle\Entity\EmployeeRepository") * @ORM\HasLifecycleCallbacks() */ class Employee { ...... |
要在入库前要在PrePersist、PreUpdate进行文件重命名并创建文件相对路径
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//src\Nlc\InformationBundle\Entity\Employee.php ... /** * @ORM\PrePersist * @ORM\PreUpdate */ public function preUpload() { $this->photouniqid=uniqid(); $this->jlfileuniqid=uniqid(); if (null !== $this->getPhotofile()) { $this->photopath = $this->getUploadDir()."/".$this->photouniqid.'photo.'.$this->getPhotofile()->guessExtension(); } if (null !== $this->getJlfile()) { $this->jlpath = $this->getUploadDir()."/".$this->jlfileuniqid.'jlfile.'.$this->getJlfile()->guessExtension(); } } ... |
好我们要上传文件了,在哪个步骤上传呢,应该在信息入库之后,我们调用PostPersist、PostUpdate来完成上传工作,代码来了很简单的哦!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
//src\Nlc\InformationBundle\Entity\Employee.php ... /** * @ORM\PostPersist * @ORM\PostUpdate */ public function photoupload() { //判断是否上传文件是否成功 if (null === $this->getPhotofile()) { return; } //完成文件上传 $this->getPhotofile()->move( $this->getUploadRootDir(), $this->photouniqid.'photo.'.$this->getPhotofile()->guessExtension() ); $this->setPhotofile(null); } /** * @ORM\PostPersist * @ORM\PostUpdate */ public function jlupload() { if (null === $this->getJlfile()) { return; } $this->getJlfile()->move( $this->getUploadRootDir(), $this->jlfileuniqid.'jlfile.'.$this->getJlfile()->guessExtension() ); $this->setJlpath(null); } ... |
$this->getPhotofile()主要判断图片是否进行了上传或者上传无误。$this->getPhotofile()->move()的意思是将上传的文件移动到指定的web指定的上传文件夹并把文件进行重命名。$this->setPhotofile(null);清空上传的文件信息。
6)删除信息时文件自动清除
1 2 3 4 5 6 7 8 9 10 11 12 |
/** * @ORM\PostRemove */ public function removeUpload() { if(file_exists($this->photopath)) { unlink($this->getRootDir().$this->photopath); } if(file_exists($this->jlpath)) { unlink($this->getRootDir().$this->jlpath); } } |
7)下面来看一下完整的src\Nlc\InformationBundle\Entity\Employee.php文件,你的思路会更清晰:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 |
//src\Nlc\InformationBundle\Entity\Employee.php <?php namespace Nlc\InformationBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\HttpFoundation\File\UploadedFile; /** * Employee * * @ORM\Table(name="employeetable") * @ORM\Entity(repositoryClass="Nlc\InformationBundle\Entity\EmployeeRepository") * @ORM\HasLifecycleCallbacks() */ class Employee { /** * @ORM\ManyToOne(targetEntity="Category",inversedBy="employees") * @ORM\JoinColumn(name="categoryid", referencedColumnName="id") */ public $category; /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * @var integer * * @ORM\Column(name="age", type="integer") */ private $age; /** * @var string * * @ORM\Column(name="sex", type="string", length=255) */ private $sex; /** * @var string * * @ORM\Column(name="education", type="string", length=255) */ private $education; /** * @var string * * @ORM\Column(name="photopath", type="string", length=255) */ private $photopath; /** * @Assert\File(maxSize="6000000") */ private $photofile; private $photouniqid; /** * @var string * * @ORM\Column(name="jlpath", type="string", length=255) */ private $jlpath; /** * @Assert\File(maxSize="6000000") */ private $jlfile; private $jlfileuniqid; /** * @var \DateTime * * @ORM\Column(name="createtime", type="datetime") */ private $createtime; /** * @var \DateTime * * @ORM\Column(name="updatetime", type="datetime") */ private $updatetime; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return Employee */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set age * * @param integer $age * @return Employee */ public function setAge($age) { $this->age = $age; return $this; } /** * Get age * * @return integer */ public function getAge() { return $this->age; } /** * Set sex * * @param string $sex * @return Employee */ public function setSex($sex) { $this->sex = $sex; return $this; } /** * Get sex * * @return string */ public function getSex() { return $this->sex; } /** * Set education * * @param string $education * @return Employee */ public function setEducation($education) { $this->education = $education; return $this; } /** * Get education * * @return string */ public function getEducation() { return $this->education; } /** * Set createtime * * @param \DateTime $createtime * @return Employee */ public function setCreatetime($createtime) { $this->createtime = $createtime; return $this; } /** * Get createtime * * @return \DateTime */ public function getCreatetime() { return $this->createtime; } /** * Set updatetime * * @param \DateTime $updatetime * @return Employee */ public function setUpdatetime($updatetime) { $this->updatetime = $updatetime; return $this; } /** * Get updatetime * * @return \DateTime */ public function getUpdatetime() { return $this->updatetime; } /** * @ORM\PrePersist */ public function setCreatetimeValue() { if(!$this->getCreatetime()) { $this->createtime = new \DateTime(); } } /** * @ORM\PreUpdate */ public function setUpdatetimeValue() { $this->updatetime = new \DateTime(); } /** * Set category * * @param \Nlc\InformationBundle\Entity\Category $category * @return Employee */ public function setCategory(\Nlc\InformationBundle\Entity\Category $category = null) { $this->category = $category; return $this; } /** * Get category * * @return \Nlc\InformationBundle\Entity\Category */ public function getCategory() { return $this->category; } /** * Set photopath * * @param string $photopath * @return Employee */ public function setPhotopath($photopath) { $this->photopath = $photopath; return $this; } /** * Get photopath * * @return string */ public function getPhotopath() { return $this->photopath; } /** * Set jlpath * * @param string $jlpath * @return Employee */ public function setJlpath($jlpath) { $this->jlpath = $jlpath; return $this; } /** * Get Jlpath * * @return string */ public function getJlpath() { return $this->jlpath; } /** * Sets photofile. * * @param UploadedFile $photofile */ public function setPhotofile(UploadedFile $photofile = null) { $this->photofile = $photofile; } /** * Get photofile. * * @return UploadedFile */ public function getPhotofile() { return $this->photofile; } /** * Sets jlfile. * * @param UploadedFile $jlfile */ public function setJlfile(UploadedFile $jlfile = null) { $this->jlfile = $jlfile; } /** * Get jlfile. * * @return UploadedFile */ public function getJlfile() { return $this->jlfile; } /** * @ORM\PrePersist * @ORM\PreUpdate */ public function preUpload() { $this->photouniqid=uniqid(); $this->jlfileuniqid=uniqid(); if (null !== $this->getPhotofile()) { $this->photopath = $this->getUploadDir()."/".$this->photouniqid.'photo.'.$this->getPhotofile()->guessExtension(); } if (null !== $this->getJlfile()) { $this->jlpath = $this->getUploadDir()."/".$this->jlfileuniqid.'jlfile.'.$this->getJlfile()->guessExtension(); } } /** * @ORM\PostPersist * @ORM\PostUpdate */ public function photoupload() { if (null === $this->getPhotofile()) { return; } // you must throw an exception here if the file cannot be moved // so that the entity is not persisted to the database // which the UploadedFile move() method does $this->getPhotofile()->move( $this->getUploadRootDir(), $this->photouniqid.'photo.'.$this->getPhotofile()->guessExtension() ); $this->setPhotofile(null); } /** * @ORM\PostPersist * @ORM\PostUpdate */ public function jlupload() { if (null === $this->getJlfile()) { return; } // you must throw an exception here if the file cannot be moved // so that the entity is not persisted to the database // which the UploadedFile move() method does $this->getJlfile()->move( $this->getUploadRootDir(), $this->jlfileuniqid.'jlfile.'.$this->getJlfile()->guessExtension() ); $this->setJlpath(null); } /** * @ORM\PostRemove */ public function removeUpload() { if(file_exists($this->photopath)) { unlink($this->getRootDir().$this->photopath); } if(file_exists($this->jlpath)) { unlink($this->getRootDir().$this->jlpath); } } protected function getRootDir() { return __DIR__.'/../../../../web/'; } protected function getUploadRootDir() { // the absolute directory path where uploaded // documents should be saved return $this->getRootDir().$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'; } } |
很容易吧!下面我们调整一些上传后,模板显示的细节。
第三步,调整页面细节
需要调整两个页面
1)src\Nlc\InformationBundle\Resources\views\Employee\show.html.twig上传后会跳转到此页显示,我们要让照片能够显示出来、让简历能够下载,而不是只显示URL。
将此页面的
1 2 3 |
<td>{{ entity.photo }}</td> <td>{{ entity.file }}</td> |
更改成
1 2 3 |
<td><img src="{{ asset(entity.photopath) }}" /></td> <td><a href="{{ entity.jlpath }}" target="_blank" >{{ entity.name }}简历下载</a> </td> |
看看上传后这个页面的效果:
虽然很简单但是功能已经实现,后面我们再美化模板。
2)在调整一下列表页以免他报错
src\Nlc\InformationBundle\Resources\views\Employee\index.html.twig
将
1 2 |
<td>{{ entity.photo }}</td> <td>{{ entity.file }}</td> |
更改成
1 2 |
<td>{{ entity.photopath }}</td> <td>{{ entity.jlpath }}</td> |
剩余的页面细节,会在整体功能完成后,更换我们自己制作的模板时,整体调整,不要着急哦。所以说下面几章也不会将我们之前的模板渲染到这个程序中,只有最后完成了主要功能我们才会进行模板的渲染。
楼主辛苦了。
从第一篇看到这里,不明白的是 sql语句执行错误了:
INSERT INTO employeetable (name, age, sex, education, photopath, jlpath, createtime, updatetime, categoryid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
这里 数据库中是photo 和 file,可程序中改成photopath 和jlpath了 这难道要 php bin/console doctrine:schema:update –force?
麻烦指点一下,谢谢
果然,需要更新一下。执行php app/console doctrine:schema:update –force页面就正常了。
我自己已经改好了,谢谢楼主的教程!
楼主,您好,我遇到了和leoric一样的问题?经过调试,我发现是因为 @ORM\PrePersist 这些事件没有生效,我用的是symfony2.8,现在还没解决,下面是我的简单的一个demo:
entity中部分代码:
<?php
namespace Nlc\InformationBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
* @ORM\HasLifecycleCallbacks()
*/
class Adminuser
{
/**
* @ORM\PrePersist
*/
public function test(){
dump(1);die;
}
}
controller中部分代码:
getDoctrine()->getManager();
$adminuser = new Adminuser();
$adminuser->setUsername(‘dave’);
$adminuser->setPassword(‘123′);
$em->persist($adminuser);
$em->flush();
return new Response();
}
}
希望前辈您看到后能回复我一下,谢谢!
你可以试试清除缓存,或者doctrine:schema:update –force
你也可以看看中文站关于这方面的文章
http://www.symfonychina.com/doc/current/doctrine/lifecycle_callbacks.html