Home > Backend Development > PHP Tutorial > Symfony2 uses the third-party library Upload to create an image upload example, _PHP tutorial

Symfony2 uses the third-party library Upload to create an image upload example, _PHP tutorial

WBOY
Release: 2016-07-12 08:59:24
Original
1136 people have browsed it

Detailed explanation of how Symfony2 uses the third-party library Upload to create image upload examples.

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": "*"

Copy after login

2. Run the command to install

composer update

Copy after login

2. Encoding

1. Write the uploadPic method to upload the image, and use the user ID of the uploaded image as the file name

<&#63;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;
  }
}

Copy after login

2. The user uploads an avatar and stores the full path of the avatar into the database table

<&#63;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 = &#63; 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 = &#63; WHERE id = &#63;", 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'));
  }
}

Copy after login

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.

Articles you may be interested in:

  • Symfony2’s method of implementing built-in data in doctrine
  • Detailed explanation of installing third-party Bundles instances with Symfony2
  • Symfony2 in Nginx Graphical tutorial on the configuration method below
  • Symfony2 installation method (2 methods)
  • Symfony2 session usage example analysis
  • High-performance PHP framework Symfony2 classic introductory tutorial
  • Ten minutes to learn Symfony classic tutorial
  • Symfony data verification method example analysis
  • Symfony form and page implementation skills
  • Symfony2 development controller usage example analysis

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1098963.htmlTechArticleSymfony2 uses the third-party library Upload to create image upload examples. This article analyzes the example of Symfony2 using the third-party library Upload to create images. Upload method. Sharing it with everyone for your reference,...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template