Symfony2 use third-party library upload to make picture upload instance _php instance

Source: Internet
Author: User
Tags codeigniter
This paper analyzes the method of Symfony2 using third-party library upload to make image uploading. Share to everyone for your reference, as follows:

We generally have the function of setting the avatar in the profile of the application or the website, this chapter we use a third party's more famous upload library to make the function of uploading the picture in Symfony2.

First, install a third-party library

1. In "require" in the Composer.json file, add

"Codeguy/upload": "*"

2. Run the command installation

Composer Update

Second, the Code

1. Write the Uploadpic method to upload the image, and upload the image as the user ID as the file name

<?php/** * @author Sun * by blogs.zmit.cn http://blogs.zmit.cn * Original works, permission to reprint, please be sure to use hyperlinks in the form of the original source of the article http://blogs.zmit.cn/ 6544.html * Chinese Dream Blog, author information and this statement. Otherwise, the legal liability will be investigated. */namespace Zm\adminbundle\controller;use Symfony\bundle\frameworkbundle\controller\controller;use Symfony\ Component\filesystem\filesystem;class Defaultcontroller extends Controller {public Function indexaction ($name) {Retu  RN $this->render (' ZMAdminBundle:Default:index.html.twig ', Array (' name ' = = $name));   /** * Upload image * * @param type $user The ID of the _id user, use as file name * @param type $str name of input of type file in form * @param type $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 not present, create directory $fs->mkdir ($path, 0700);    }//using Upload library $storage = new \upload\storage\filesystem ($path);    $file = new \upload\file ($STR, $storage); If the file name is null if ($file->getname ()! = ") {//sets the file name to the user's ID $file->setname ($user _id); Verify File Upload $file->addvalidations (Array (//Specify file Type new \upload\validation\mimetype (Array (' image/png ', ' I      Mage/jpg ', ' image/jpeg ', ' image/gif '),//Specify File Size new \upload\validation\size (' 2M '));        Upload file try {//Success $file->upload ();      File name and extension $file _name = $file->getnamewithextension ();        } catch (\exception $e) {//failed!      $errors = $file->geterrors ();  }}//Return file name and extension return $file _name; }}

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

<?php/** * Contact Controller * @author Sun * by blogs.zmit.cn http://blogs.zmit.cn * Original works, permission to reprint, please be sure to use hyperlinks in the form of the original source of the article http://blogs.z mit.cn/6544.html * Chinese Dream Blog, author information and this statement. Otherwise, the legal liability will be investigated. */namespace zm\apibundle\controller;//refer to the Uploadpic Controller that wrote the upload image method and named Basecontrolleruse zm\adminbundle\ Controller\defaultcontroller as Basecontroller;use symfony\component\httpfoundation\request;use Symfony\Component\  httpfoundation\response;//inherit Basecontrollerclass Contactcontroller extends Basecontroller {/** * user uploads avatar * * @return    Response */Public 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 ()->get      Connection (); $data = $conn-&GT;FETCHASSOC ("Select ID, head from the contact 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 file name and extension $file _name = $this->uploadpic ($user _id, ' head ', $path) returned after uploading the files; Modify the value of the user Contact table Head picture field $conn->executeupdate ("UPDATE contact SET head =?")        WHERE id =? ", Array ($path. $file _name, $user _id));        $result [' flag '] = 1; $result [' content '] = ' upload avatar successfully!      ';        } else {$result [' flag '] = 3; $result [' content '] = ' user does not exist!      ';      }}else{$result [' flag '] = 2; $result [' content '] = ' upload failed, no picture Selected!    ';  } return new Response (Json_encode ($result), ' n ', Array (' content-type ' = ' Application/json ')); }}

So the picture is uploaded successfully, the user's ID as the file name, and modify the table field value as the full path of the picture

Permanent address of this article: http://blog.it985.com/6544.html
This article is from IT985 blog, please indicate the source and corresponding link when reproduced.

Read more about PHP framework related content Readers can view this site: "PHP Excellent Development Framework Summary", "CodeIgniter Introductory Tutorial", "CI (codeigniter) Framework Advanced Tutorial", "Yii framework Introduction and common skills Summary" and " thinkphp Getting Started Tutorial "

It is hoped that this article is helpful to 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.