This article analyzes the method of Symfony2 using the third-party library Upload to create image uploads. Share it with everyone for your reference, the details are as follows:
We generally have the function of setting avatars in the personal information of applications or websites. In this chapter, we use a well-known third-party Upload library in Symfony2 to create the function of uploading pictures.
1. Install third-party libraries
1. Add
to "require" in the composer.json file"codeguy/upload": "*"
2. Run the command to install
composer update
2. Encoding
1. Write the uploadPic method to upload the image, and use the user ID of the uploaded image as the file name
<?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. The user uploads an avatar and stores the full path of the avatar into the database table
<?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')); } }
In this way, the image is uploaded successfully, use the user's id as the file name, and modify the table field value to the full path of the image
The permanent address of this article: http://blog.it985.com/6544.html
This article comes from IT985 Blog. Please indicate the source and corresponding link when reprinting.
Readers who are interested in more content related to the PHP framework can check out the special topics of this site: "Summary of PHP Excellent Development Framework", "Introduction Tutorial on Codeigniter", "Advanced Tutorial on CI (CodeIgniter) Framework", "Introduction to Yii Framework and Summary of common techniques" and "ThinkPHP introductory tutorial"
I hope this article will be helpful to everyone’s PHP program design based on the Symfony framework.