本文实例分析了Symfony2使用第三方库Upload制作图片上传的方法。分享给大家供大家参考,具体如下:
我们在应用程序或者网站的个人资料里一般都有设置头像的功能,这一章我们在Symfony2里用第三方的一个比较有名Upload库来制作上传图片的功能。
一、安装第三方库
1.在composer.json文件中的”require”中加入
"codeguy/upload": "*"
2.运行指令安装
composer update
二、编码
1.编写uploadPic方法上传图片,并将上传图片的用户id作为文件名
<?php /** * @author Sun * By blogs.zmit.cn http://blogs.zmit.cn * 原创作品,允许转载,转载时请务必以超链接形式标明文章原始出处 http://blogs.zmit.cn/6544.html * 中梦博客,作者信息和本声明。否则将追究法律责任。 */ namespace ZM\AdminBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Filesystem\Filesystem; class DefaultController extends Controller { public function indexAction($name) { return $this->render('ZMAdminBundle:Default:index.html.twig', array('name' => $name)); } /** * 上传图片 * * @param type $user_id 用户的id,用作文件名 * @param type $str 表单中file类型的input的name * @param type $path 保存路径 * @return type */ public function uploadPic($user_id, $str, $path) { $fs = new Filesystem(); //检查路径是否存在 if (!$fs->exists($path)) { //如果不存在,创建目录 $fs->mkdir($path, 0700); } //使用Upload库 $storage = new \Upload\Storage\FileSystem($path); $file = new \Upload\File($str, $storage); //如果文件名为空 if ($file->getName() != '') { //设置文件名为用户的id $file->setName($user_id); //验证文件上传 $file->addValidations(array( //指定文件类型 new \Upload\Validation\Mimetype(array('image/png', 'image/jpg', 'image/jpeg', 'image/gif')), //指定文件大小 new \Upload\Validation\Size('2M') )); //上传文件 try { //成功 $file->upload(); //文件名和扩展名 $file_name = $file->getNameWithExtension(); } catch (\Exception $e) { //失败! $errors = $file->getErrors(); } } //返回文件名和扩展名 return $file_name; } }
2.用户上传头像,并将头像全路径存入数据库表
<?php /** * 联系人控制器 * @author Sun * By blogs.zmit.cn http://blogs.zmit.cn * 原创作品,允许转载,转载时请务必以超链接形式标明文章原始出处 http://blogs.zmit.cn/6544.html * 中梦博客,作者信息和本声明。否则将追究法律责任。 */ namespace ZM\ApiBundle\Controller; //引用写好的上传图片方法uploadPic的Controller,并命名为BaseController use ZM\AdminBundle\Controller\DefaultController AS BaseController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; //继承BaseController class ContactController extends BaseController { /** * 用户上传头像 * * @return Response */ public function uploadHeadAction() { $request = Request::createFromGlobals()->request; $user_id = $request->get('user_id'); //判断是否有文件上传 if (isset($_FILES['head']) && $_FILES['head'] != '') { $conn = $this->getDoctrine()->getConnection(); $data = $conn->fetchAssoc("SELECT id, head FROM contact WHERE id = ? LIMIT 1", array($user_id)); //判断用户是否存在 if(!empty($data['id'])) { //设置图片保存路径 $path = 'image/head/'; //获取上传文件后返回的文件名和扩展名 $file_name = $this->uploadPic($user_id, 'head', $path); //修改用户contact表head头像字段的值 $conn->executeUpdate("UPDATE contact SET head = ? WHERE id = ?", array($path . $file_name, $user_id)); $result['flag'] = 1; $result['content'] = '上传头像成功!'; } else { $result['flag'] = 3; $result['content'] = '用户不存在!'; } }else{ $result['flag'] = 2; $result['content'] = '上传失败,没有选择图片!'; } return new Response(json_encode($result), '200', array('Content-Type' => 'application/json')); } }
这样图片就上传成功,将用户的id作为文件名,并修改表字段值为图片的全路径
本文永久地址:http://blog.it985.com/6544.html
本文出自 IT985博客 ,转载时请注明出处及相应链接。
更多关于PHP框架相关内容感兴趣的读者可查看本站专题:《php优秀开发框架总结》,《codeigniter入门教程》,《CI(CodeIgniter)框架进阶教程》,《Yii框架入门及常用技巧总结》及《ThinkPHP入门教程》
希望本文所述对大家基于Symfony框架的PHP程序设计有所帮助。

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor
