Symfony2 Use the third party library upload to create pictures upload examples _php examples

Source: Internet
Author: User
Tags php framework codeigniter

This article analyses the method of Symfony2 using the third party library upload to make picture uploading. Share to everyone for your reference, specific as follows:

We generally have the function of setting avatar in the personal data of the application or the website, this chapter we use a third party in Symfony2 to make the function of uploading the picture with a relatively famous upload library.

First, install the third Party library

1. Add in "require" in the Composer.json file

"Codeguy/upload": "*"

2. Operation instruction Installation

Composer Update

Second, coding

1. Write the Uploadpic method upload picture, and upload the image of the user ID as the filename

<?php/** * @author Sun * by blogs.zmit.cn http://blogs.zmit.cn * Original works, allow reprint, reprint, please be sure to hyperlink form to indicate the original source of the article Http://blogs.zmit. cn/6544.html * Dream Blog, author information and this statement.
 Otherwise, legal liability will be held.
* * 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 (' Zmadminbu
  Ndle:Default:index.html.twig ', Array (' name ' => $name));  /** * Upload Picture * * @param type $user _id user ID, used as filename * @param type $STR the name * @param type of the file type input in the form
    $path Save Path * @return Type */Public function uploadpic ($user _id, $str, $path) {$fs = new filesystem ();
    Check if the path exists if (! $fs->exists ($path)) {//If it does not exist, create a directory $fs->mkdir ($path, 0700);
    ///Use Upload library $storage = new \upload\storage\filesystem ($path);
    $file = new \upload\file ($STR, $storage); If the file name is an empty if ($file->getname ()!= '' {//Set file name as User ID $file->setname ($user _id);  Verify that the file is uploaded $file->addvalidations (Array (//) specifies the file type new \upload\validation\mimetype (' Image/png ',
      ' Image/jpg ', ' image/jpeg ', ' image/gif '),//Specify File Size new \upload\validation\size (' 2M '));
        Upload file try {//Success $file->upload ();
      The filename and extension $file _name = $file->getnamewithextension ();
        catch (\exception $e) {//failed!
      $errors = $file->geterrors ();
  }//returns the filename and extension return $file _name;

 }
}

2. The user uploads the avatar, and the avatar full path is stored in the database table

<?php/** * Contact Controller * @author Sun * by blogs.zmit.cn http://blogs.zmit.cn * Original works, allow reprint, reprint, please be sure to hyperlink form to indicate the original source of the article http://b logs.zmit.cn/6544.html * Dream Blog, author information and this statement.
 Otherwise, legal liability will be held.
* * Namespace Zm\apibundle\controller; Reference to the written upload image method Uploadpic Controller, and named Basecontroller use Zm\adminbundle\controller\defaultcontroller as
Basecontroller;
Use Symfony\component\httpfoundation\request;
Use Symfony\component\httpfoundation\response; Inherit Basecontroller class Contactcontroller extends Basecontroller {/** * user upload avatar * * @return Response/P
    ublic function Uploadheadaction () {$request = Request::createfromglobals ()->request;
    $user _id = $request->get (' user_id '); Determine if there is a file upload if (isset ($_files[' head ')) && $_files[' head ']!= ') {$conn = $this->getdoctrine ()->g
      Etconnection (); $data = $conn-&GT;FETCHASSOC ("Select ID, head from contacts WHERE id =?")
      LIMIT 1 ", Array ($user _id));
Determine if the user exists if (!empty ($data [' ID '])} {//Set Picture save path        $path = ' image/head/';
        Gets the filename and extension $file _name = $this->uploadpic ($user _id, ' head ', $path) after uploading the file Modify the value of the user Contact table Head avatar field $conn->executeupdate ("UPDATE contact SET heads =?").
        WHERE id =? ", Array ($path. $file _name, $user _id));
        $result [' flag '] = 1; $result [' content '] = ' upload avatar success!
      ';
        else {$result [' flag '] = 3; $result [' content '] = ' user does not exist!
      ';
      }}else{$result [' flag '] = 2; $result [' content '] = ' upload failed, no pictures selected!
    ';
  Return to New Response (Json_encode ($result), ' m ', Array (' Content-type ' => ' Application/json '));

 }
}

The image is uploaded successfully, the user ID as the file name, and the table field value is the full path of the picture

This article permanent address: http://blog.it985.com/6544.html
This article comes from IT985 blog, reprint, please indicate the source and corresponding link.

For more information about PHP framework interested readers can view the site topics: "PHP Excellent Development Framework Summary", "CodeIgniter Introductory Course", "CI (CodeIgniter) Framework Advanced Course", "Yii framework Introduction and common skills Summary" and " thinkphp Getting Started Tutorial "

I hope this article will help you with the PHP program design based on Symfony framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.